Caomu - 1 year ago 54

R Question

I am beginner of R, I met a problem which might be simple for you. Thanks in advance if could give me some help. I am not sure whether the title does reflect the problem I want to ask. To make my problem clear, I will use a simple example.

Let's say we have data frame containing two factors (FE and DI) and three variables (SR1, SR2 and SR3) like:

`df<-data.frame(FE=rep(c("FL","FM","FH"),4),DI=rep(c("DL","DH"),each=6),`

SR1=rpois(12,10),SR2=rpois(12,15),SR3=rpois(12,20))

I know how to calculate the means of variables according to the factors by using "aggregate", for example:

`df.me1<-aggregate(SR1~FE,df,mean)`

df.me2<-aggregate(cbind(SR1,SR2,SR3)~FE+DI,df,mean)

Then, I make two characters (vars and facs) consisting of names of the three variables and the two factors:

`vars<-c("SR1","SR2","SR3")`

facs<-c("FE","DI")

Now, I want to do the calculations in the following formula for some reason

`df.me1<-aggregate(vars[1]~facs[1],df,mean)`

df.me2<-aggregate(cbind(vars[1],vars[2],vars[3])~facs[1]+facs[2],df,mean)

The codes certainly do not work, so what should I do to make them work in this way?

Answer Source

@jdobres' answer is cleaner and probably better in most instances, but if you must do this exactly as you've written it, then referencing this answer, you can just use `get()`

.

```
df.me2<-aggregate(cbind(SR1,SR2,SR3)~FE+DI,df,mean)
df.me2.get<-aggregate(cbind(get(vars[1]),get(vars[2]),get(vars[3]))~get(facs[1])+get(facs[2]),df,mean)
```

And checking if they are the same:

```
df.me2 == df.me2.get
FE DI SR1 SR2 SR3
[1,] TRUE TRUE TRUE TRUE TRUE
[2,] TRUE TRUE TRUE TRUE TRUE
[3,] TRUE TRUE TRUE TRUE TRUE
[4,] TRUE TRUE TRUE TRUE TRUE
[5,] TRUE TRUE TRUE TRUE TRUE
[6,] TRUE TRUE TRUE TRUE TRUE
```