This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Removing four columns with the same name and position from 38 data.frames in R

Hello,

I would like to remove the same four columns from 38 data.frame using either function(), lapply, or a for loop.

Below are the four versions of my code that I ran; none of them worked.

Version 1:

f1 <- function(lib){
  lib <- subset(lib, select = -c(TranscriptID, group_name, width.x, width.y))
}

f1(df2)
...
f1(df39)

version 2:

f1 <- function(X){
  X = X %>% select(-TranscriptID, -group_name, -width.x, -width.y)
  names(X)
}

f1(df2)
...
f1(df39)

version 3:

list_dfs <- dplyr::lst(df2, df3, df4,..., df39)

list_dfs <- lapply(list_dfs, function(x) x[names(x) != "TranscriptID", 
                                           "group_name", "width.x", "width.y"])
list2env(list_dfs, .GlobalEnv)

version 4:

list_dfs <- dplyr::lst(df2, df3, df4,..., df39)

list_dfs2 <- lapply(list_dfs, subset, select = -col1, -col2, -col4, -col8)
list2env(list_dfs2, .GlobalEnv)

Note: "TranscriptID", "group_name", "width.x", and "width.y" are the column names of columns 1, 2, 4, and 8 in all the dfs.

Thank you for your assistance, Stef

loop remove r columns data.frame

2 answers

lapply(list_dfs, \(x) x[, -c(1, 2, 4, 8)])

There's a little trick shortcut you can do too.

lapply(list_dfs, `[`, , -c(1, 2, 4, 8))

To fix your existing code, we need %in% :

list_dfs <- lapply(list_dfs, function(x) x[ !names(x) %in% c("TranscriptID", "group_name", "width.x", "width.y") ])

Log in to answer this question.