1

Suppose I have:

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

I want to read data from variables in a for loop like:

for((i in 1: 4){
  y<- dat$paste("x",i,sep="")
  sum(y)
}

How can I make it to work?

I want to do many calculations on each (column) variable x1, x2, etc

  • 1
    Are you just trying to do row or column sums? R has both `rowSums` and `colSums` functions to help you out there. – hrbrmstr Apr 22 '14 at 20:31
  • Alternatively, you can use apply() to run commands or more complex functions row- or column-wise. I think you would want y=apply(dat,1,sum). – David Roberts Apr 22 '14 at 20:35
  • Your `$paste` construction is invalid. You can use `paste` inside `[]` but not with `$` extraction. You should read up on [the relevant documentation](http://stat.ethz.ch/R-manual/R-devel/library/base/html/Extract.html). – Thomas Apr 22 '14 at 20:35
  • I want to do many calculations on the column variables x1,x2,x3... – user3561989 Apr 22 '14 at 20:45
  • @user3561989, then you need `apply` family functions, by columns you should use `y <- apply(dat, 2, sum)` or instead `sum` any other function – user2380782 Apr 22 '14 at 21:36
  • some more info in an [**old answer of mine**](http://stackoverflow.com/a/18228613/1478381). – Simon O'Hanlon Apr 22 '14 at 23:04

1 Answers1

0

Learn to use the "[[" function ... because you cannot do what you wanted with "$":

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
IRTFM
  • 258,963
  • 21
  • 364
  • 487