0

I have three measures in my dataset that I am trying to combine into one new variable that represents the mean value across those three variables for each row in turn (each row represents a participant). Each of the original three variables contains NA values.

I've tried the code below that I've applied here to a sample dataset from R that contains NA values (airquality):

airquality %>% mutate(New = mean(airquality$Solar.R,airquality$Ozone,airquality$Wind))

But I keep getting the error message:

Error in mean.default(airquality$Solar.R, airquality$Ozone, airquality$Wind) : 'trim' must be numeric of length one In addition: Warning message: In if (na.rm) x <- x[!is.na(x)] : the condition has length > 1 and only the first element will be used

I have also tried :

airquality %>% filter(!is.na(airquality$Solar.R,airquality$Ozone,airquality$Wind)) %>%  mutate(New = mean(airquality$Solar.R,airquality$Ozone,airquality$Wind))

But this gives me the same error.

Can anyone advise on how to solve this problem?

Thanks so much in advance!

2
  • Try : airquality %>% mutate(New = rowMeans(.[c("Solar.R", "Ozone", "Wind")], na.rm = T)) Jul 30, 2019 at 9:48
  • @A.Suliman - thank you so much, your code airquality %>% rowwise()%>%mutate(New = mean(c(Solar.R,Ozone,Wind), na.rm = TRUE)) worked perfectly.
    – Sarah
    Jul 30, 2019 at 9:59

1 Answer 1

1

You can use row_mean_ from hablar which takes mean by row while ignoring missing.

library(hablar)
airquality %>% 
  mutate(New = row_mean_(Solar.R, Ozone, Wind))

Result

    Ozone Solar.R Wind Temp Month Day        New
1      41     190  7.4   67     5   1  79.466667
2      36     118  8.0   72     5   2  54.000000
3      12     149 12.6   74     5   3  57.866667
4      18     313 11.5   62     5   4 114.166667
5      NA      NA 14.3   56     5   5  14.300000
6      28      NA 14.9   66     5   6  21.450000
7      23     299  8.6   65     5   7 110.200000

Not the answer you're looking for? Browse other questions tagged or ask your own question.