msoftrain msoftrain - 1 month ago 8
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
apply()
within the function
with()
.

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

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))