user552231 user552231 - 1 month ago 7
R Question

object not find when aggregating in R

I am trying to use aggregate in R. I found an example code:

attach(mtcars)
agg=aggregate(mtcars, by=list(cyl,vs),FUN=mean, na.rm=TRUE)
detach(mtcars)


This works fine. However when I try to do it using my data:

library(stats)
FileName="Raw.csv"
Raw=read.csv(FileName,header = TRUE)
Acc1=aggregate(Raw,by=list(Experiment,SsNum),FUN=mean, na.rm=TRUE)


I get the following error message:

Error in aggregate.data.frame(Raw, by = list(Experiment, SsNum), FUN = mean, object 'Experiment' not found

I also tries to run:

Acc2=aggregate(Raw,by=list(Raw$Experiment,Raw$SsNum),FUN=mean, na.rm=TRUE)


and I got the following error:

There were 50 or more warnings (use warnings() to see the first 50)

The warnings are:
1: In mean.default(X[[i]], ...) :
argument is not numeric or logical: returning NA

my main question is how the Acc1 is differrent from the online example (that works fine).

thank you very much

Ariel

Answer

you can just compute the mean of a numeric variable so you have at least to take a subset of the data excluding character variables. Thats were you ACC1 most likely differ from mtcars, because in mtcars there are only numeric values in, due to this you do not get a warning in the first line.

So in this line:

Acc2=aggregate(Raw,by=list(Raw$Experiment,Raw$SsNum),FUN=mean, na.rm=TRUE)

You get a error, because in RAW there appears to be column which are not numeric

Supposed you have:

set.seed(4)
Experiment <- sample(seq(1:3), 5, replace=TRUE)
SsNum <- sample(1:10, 5, replace=TRUE)
value <- rnorm(5)
df <- data.frame(Experiment, SsNum, value)

Then aggregate works as follows:

aggregate(value ~Experiment + SsNum, data = df, FUN = mean)
  Experiment SsNum      value
1          3     1  1.7768632
2          2     3  0.6892754
3          1     8 -1.2812466
4          1    10  0.8416977