Removing four columns with the same name and position from 38 data.frames in R
2
0
Entering edit mode
18 months ago
Estefania ▴ 30

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 • 931 views
ADD COMMENT
1
Entering edit mode
18 months ago
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))
ADD COMMENT
0
Entering edit mode

Thank you. It worked!

ADD REPLY
1
Entering edit mode
18 months ago
zx8754 12k

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") ])
ADD COMMENT

Login before adding your answer.

Traffic: 1589 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6