我有一个名为SAL_mean的变量就是这样创建的(我希望在我弄清楚之后创建一个循环):
watersheds <- c('ANE', 'SAL', 'CER')
assign(paste0(watersheds[1], '_mean'), read.csv(paste0(watersheds[1], '_mean.csv')))
现在下一步应该是这样的(有效):
cols_dont_want <- c('B1', 'B2', 'B3')
assign(paste0(watersheds[1], '_mean'), SAL_mean[, !names(SAL_mean) %in% cols_dont_want])
但我想问一下如何替换&#34; SAL_mean&#34;通过使用分水岭[1],因为这行代码不起作用:
assign(paste0(watersheds[1], '_mean'), paste0(watersheds[1], '_mean')[, !names(paste0(watersheds[1], '_mean')) %in% cols_dont_want])
我认为它对待&#34; paste0(分水岭[2],&#39; _mean&#39;)&#34;作为字符串,而不是变量的名称,但我还没有找到解决方案(我尝试过例如&#34; as.name&#34;函数但它给了我一个错误&#34;对象type&#39; symbol&#39;不是子集表格&#34;)
答案 0 :(得分:5)
使用?lapply
将数据帧保留在列表中,然后更容易在列表中的多个数据帧上执行相同的转换,例如:
# set vars
watersheds <- c('ANE', 'SAL', 'CER')
cols_dont_want <- c('B1', 'B2', 'B3')
# result, all dataframes in one list
myList <- lapply(watersheds, function(i){
# read the file
x <- read.csv(paste0(i, "_mean.csv"))
# exclude columns and return
x[, !colnames(x) %in% cols_dont_want]
} )
答案 1 :(得分:1)
或者你可以在for循环中执行它(有些人发现语法更容易理解)。它等同于zx8754的解决方案,除了它根据OP为每个数据帧分配名称。修改zx8754的解决方案做同样的事情是微不足道的。
watersheds <- c('ANE', 'SAL', 'CER')
cols_dont_want <- c('B1', 'B2', 'B3')
ws.list <- list()
for (i in 1:length(watersheds)) {
ws.list[[i]] <- read.csv(paste0(watersheds[i], '_mean.csv'))
names(ws.list)[i] <- paste0(watersheds[i], '_mean')
ws.list[[i]] <- ws.list[[i]][!names(ws.list[[i]]) %in% cols_dont_want]
}
names(ws.list)
# "ANE_mean" "SAL_mean" "CER_mean"
# If you absolutely want to call the data.frames by their
# individual names, you can do so after you attach() the list.
attach(ws.list)
ANE_mean
答案 2 :(得分:-1)
替换
paste0(watersheds[2], '_mean')
带
eval(parse(text = paste0(watersheds[2], '_mean')))
它应该有效。你的猜测是正确的,paste0只是给你一个字符串,但你需要调用使用eval()完成的变量