R- for循环在数据帧中选择两列,只有第二列改变



我在r中编写for循环时遇到了问题。我有一个16列94行的数据帧,我想循环,选择列1,加上列2在一个数据帧中,然后col 1 + col 3等,所以我最终有16个数据帧包含2列,所有写入单独的。csv文件

TwoB<- read.csv("data.csv", header=F) 
list<- lapply(1:nX, function(x) NULL)

nX <- ncol(TwoB)
for(i in 1:ncol(TwoB)){
list[[i]]<-subset(TwoB,
select=c(1, i+1))
}

产生错误:

Error in `[.data.frame`(x, r, vars, drop = drop): 
undefined columns selected

我不太确定如何编写这个代码,显然还没有完全掌握循环,所以任何帮助都会很感激!

这个错误很容易解释,因为您遍历16列,最后尝试选择16+1,其中列索引不存在。你也许可以在nX-1上循环,但我认为你想要达到的效果可以做得更优雅。

TwoB<- read.csv("data.csv", header=F)
library("data.table")
setDT(TwoB)
nX <- ncol(TwoB)
# example to directly write your files
lapply(2:nX, function(col_index) {
fwrite(TwoB[, c(1, ..col_index)], file = paste0("col1_col", col_index, ".csv"))
})
# example to store the new data.tables in a list
list_of_two_column_tables <- lapply(2:nX, function(col_index) {
TwoB[, c(1, ..col_index)]
})

最新更新