如果我有序列,请说:
a <- (seq(from=10, to=ncol(x), by=2))
b <- (seq(from=16, to=ncol(x), by=2))
我希望根据顺序访问data.frame
中的特定列,我将如何在R中执行此操作?
手动我想要这个:
y <- df[, c(10:16, 12:18, 14:20 )]
自动我需要这样的东西:
y<-df[, c(a[1]:b[1], a[2]:b[2])]
但这不起作用。
你有什么建议吗?非常感谢!我试图自己找到解决方案,但失败了。
答案 0 :(得分:1)
使用相同的向量a
和b
作为@CathG,您也可以使用mapply
:
y <- x[, mapply(seq, a, b)]
或更快的版本
y <- x[, mapply(`:`, a, b)]
答案 1 :(得分:0)
假设没有长度问题(a
和b
具有相同的长度),例如
a<-seq(from=10, to=ncol(x)-6, by=2)
b<-seq(from=16, to=ncol(x), by=2)
你可以这样做:
y<-df[, as.vector(apply(cbind(a,b),1,function(x){x[1]:x[2]}))]