我正在尝试使用列名从表文件中提取一系列列以指定范围。我试过了
dayTable[c("Peter":"Michael")]
得到了
Error in "Peter":"Michael" : NA/NaN argument
In addition: Warning messages:
1: In `[.data.frame`(dayTable, c("Peter":"Michael")) :
NAs introduced by coercion
2: In `[.data.frame`(dayTable, c("Peter":"Michael")) :
NAs introduced by coercion
答案 0 :(得分:3)
这可能会对您有所帮助:
dayTable[do.call(seq, as.list(match(c("name1", "nameN"), names(dayTable))))]
答案 1 :(得分:1)
这样的事情:
dayTable[, paste0("name",seq_len(N))]
一个完整的例子:
set.seed(1)
dayTable <-
data.frame(matrix(round(rnorm(5*5),2),ncol=5))
dayTable <-
setNames(dayTable,paste0('name',seq_len(ncol(dayTable))))
N<-4
dayTable[, paste0("name",seq_len(N))]
# name1 name2 name3 name4
# 1 -0.63 -0.82 1.51 -0.04
# 2 0.18 0.49 0.39 -0.02
# 3 -0.84 0.74 -0.62 0.94
# 4 1.60 0.58 -2.21 0.82
# 5 0.33 -0.31 1.12 0.59
nn <- names(dayTable)[order(names(dayTable))]
dayTable[, nn[nn>"name2" & nn<"name5"]]
## in your case change by Peter and karen
# name3 name4
# 1 1.51 -0.04
# 2 0.39 -0.02
# 3 -0.62 0.94
# 4 -2.21 0.82
# 5 1.12 0.59