1

I am having a terrible time trying to figure this one out. Tried a bunch of techniques/functions and so far nothing working for me and having a tough time understanding why not...

I have a data frame that has the following format:

Place          May    Jun    July    Aug    Sep    Oct
Placename1     11.1   12.5   13.6    18.9   23.10  34.7
Etc...

Place is a factor, the numerics are type double.

What I need is a column added of the mean of the monthly values for each place, like:

Place                 Mean           
Placename1           18.98   

Nothing I've done has worked to calculate the mean PER row and add to the data frame. Like I tried this:

place_df1$means <- rowMeans(place_df1)

which didn't work. Error returned:

Error in rowMeans(county_temp) : 'x' must be numeric

and I've tried literally ten different other ways, using apply, etc. Tearing what's left of my hair out. :)

Any clue on what I'm doing wrong is appreciated.

Thanks!

mswhitehead
  • 79
  • 1
  • 7
  • 6
    maybe you need `rowMeans(place_df1[,-1])` so that you exclude the first column (of characters) when computing means – d.b Jul 07 '17 at 20:43
  • 1
    That did it! And my brain's fried atm. What is that doing to the index of the column? Ah! Got you. Have no idea what I was thinking there. Thanks a bunch! – mswhitehead Jul 07 '17 at 20:47
  • have a look at `sapply(place_df1,class)` to know each column type – Vincent Guyader Jul 07 '17 at 20:47
  • So that's just peeling off the factor column? Such an easy fix. Thanks! – mswhitehead Jul 07 '17 at 20:49
  • `place_df1%>% group_by(Place) %>% ungroup() %>% mutate(means = rowMeans(.[,-1]))` In case interested in using dplyr in future. Of course stick to @d.b solution for this one. – M-- Jul 07 '17 at 20:49
  • @Masoud I've been using dplyr a lot throughout the code for other things but I'll remember that one for the future. Thanks! – mswhitehead Jul 07 '17 at 20:52

0 Answers0