I have a list if tables:
tables <- lapply(file_list, read.csv, header = F, sep="\t")
I would like to remove the column V25
, for those tables that have this column
Tried this (which does not work):
for (i in 1:length(file_list)) {
as.data.frame(tables[[i]])$V25 <- NULL
}
CodePudding user response:
Something like: lapply(list(mtcars, iris), \(x) x[,-length(x)])
?
So in your example, you could do:
lapply(lapply(file_list, read.csv, header = F, sep="\t"),\(x) x[,-length(x)])
CodePudding user response:
You may setdiff
to a vector of names to be excluded.
lapply(list.files('./foo1/', full.names=TRUE), read.csv) |>
{\(.) lapply(., \(.) .[setdiff(names(.), c("V25"))])}()
# [[1]]
# X1 X2 X3 X4
# 1 1 4 7 10
# 2 2 5 8 11
# 3 3 6 9 12
#
# [[2]]
# X1 X2 X3
# 1 1 4 7
# 2 2 5 8
# 3 3 6 9
#
# [[3]]
# X1 X2 X3 X4
# 1 1 4 7 10
# 2 2 5 8 11
# 3 3 6 9 12
#
# [[4]]
# X1 X2 X3
# 1 1 4 7
# 2 2 5 8
# 3 3 6 9
#
# [[5]]
# X1 X2 X3 X4
# 1 1 4 7 10
# 2 2 5 8 11
# 3 3 6 9 12
Note: R >= 4.1 used.
Data:
df1 <- df2 <- data.frame(matrix(1:12, 3, 4))
names(df2)[4] <- 'V25'
Map(\(x, y) write.csv(x, file=y, row.names=F), list(df1, df2, df1, df2, df1), sprintf('./foo1/%s.csv', paste0('tb', 1:5)))
df1
# X1 X2 X3 X4
# 1 1 4 7 10
# 2 2 5 8 11
# 3 3 6 9 12
df2
# X1 X2 X3 V25
# 1 1 4 7 10
# 2 2 5 8 11
# 3 3 6 9 12