在 R 中安排数据进行处理时,通常需要完成一些琐碎的转换。
考虑以下因素:
- 我想访问对象
some_set
的 N 个成员 - 具体字段:
someset$example1
、someset$example2
、...、someset$exampleN
- 我打算根据这些字段的迭代获得一个新字段。例如,映射 N 个二进制字段 ∋ ∃ ℕε[0,N]
直观上,使用这样的东西是有意义的:
for (i in 1:N ) {
doSomething( get(paste0("someset$example",i,sep='')) )
}
但是这会产生:找不到对象'someset$example1'
当然,在控制台中输入 someset$example1
确实会产生正确的值。
引出一个问题,如果 get(str)
是我们访问对象的方式,那么我们如何访问对象的字段?
最佳答案
尝试使用 [
或 [[
而不是 $
for(i in 1:N){ print(mean(someset[[paste0('example', i)]]))}
#[1] 3
#[1] 8
#[1] 13
注意:根据问题的不同,您可能不需要 for
循环。对于上述情况,使用 colMeans
会更容易。
如果“someset”是一个字符串
Var <- "someset"
for(i in 1:N){ print(mean(get(Var)[[paste0('example', i)]]))}
#[1] 3
#[1] 8
#[1] 13
数据
someset <- data.frame(example1=1:5, example2=6:10, example3=11:15)
N <- ncol(someset)
关于R:基于字符串访问对象字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29788318/