user552231 user552231 - 1 year ago 69
R Question

object not find when aggregating in R

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

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

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

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


Answer Source

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:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download