假设我有:
dat
x1 x2 x3 x4
1 1 2 3 4
2 2 3 4 5
3 3 4 5 6
4 4 5 6 7
我想从for循环中的变量中读取数据,如:
for((i in 1: 4){
y<- dat$paste("x",i,sep="")
sum(y)
}
如何让它发挥作用?
我想对每个(列)变量x1,x2等进行很多计算
答案 0 :(得分:0)
学习使用“[[”功能...因为你不能用“$”做你想做的事:
y <- numeric(0) # define a vector of numeric class
for((i in 1: 4){
y <- dat[[ paste("x",i,sep="")]] #
print(sum(y)) # you would not have seen anything that was happening inside the loop otherwise
}
y # only the last assignment would be preserved