msoftrain msoftrain - 1 year ago 66
R Question

R: apply() function in with() function

Suppose a dataset where 10 participants have filled out a questionnaire with 3 items, x, y, and z.

ss <- data.frame(x=rnorm(10), y=rnorm(10), z=rnorm(10))

I want to compute the mean of these items for each person (personal mean).
I can easily do that this way:

ss$personalmean <- rowMeans(ss[c("x", "y", "z")])

or this way:

ss$personalmean <- apply(ss[c("x", "y", "z")], 1, mean)

But suppose I want to be able to do that in the with function. Then I run into problems.

This works:

with(ss, (x+y+z)/3)

But this doesn't:

with(ss, rowMeans(c(x,y,z)))
with(ss, apply(c(x,y,z), 1, mean))

I don't understand why. The example here is trivial, but in short, I would like to use the function
within the function

Apologies if someone posted a good answer to that question somewhere, but googling what I'm looking for isn't easy given that "with" is a pretty generic term.

Answer Source

As @Frank mentioned in the comments, the apply and rowMeans work with matrix/data.frame. So, if we want to use with, instead of c, cbind converts it to matrix,

with(ss, rowMeans(cbind(x,y,z)))
with(ss, apply(cbind(x,y,z), 1, mean))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download