2

I am a beginner of R, recently I met some troubles in creating a new variable with mutate() function. The data frame "evs" has six variables:v1,v2,v3,v4,v5,v6. I hope to calculate their average and assign the average to a new variable "intp.trust" ,so I use the following commands:

evs <- mutate(evs,intp.trust= mean("v1","v2","v3","v4","v5","v6"))

But the new varriable "intp.trust" turns to have only NA. Is there anything wrong with my command? I hope someone can help me with it.

Xingchen LIU
  • 91
  • 1
  • 4

3 Answers3

1

Use rowMeans as it is vectorized

library(dplyr)
evs <- evs %>% 
   mutate(intp.trust = rowMeans(across(v1:v6), na.rm = TRUE))
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Edit: Corrected, I missed out the required c

I believe mean doesn't work over multiple vectors, so you need to tell dplyr to do the operation row-by-row. You can do this by using the "rowwise" function, i.e.:

evs <- evs %>% rowwise() %>%
  mutate(intp.trust = mean(c(v1, v2, v3, v4, v5, v6)))
Samuel B
  • 36
  • 2
0

In dplyr

evs %>% rowwise() %>% mutate(intp.trust = mean(v1:v4))

Another solution:

evs$intp.trust <- apply(evs[1:6], 1, mean, na.rm = TRUE)

Output:

      v1       v2       v3       v4 intp.trust
1 3.386651 7.651824 3.537067 7.490539   5.516520
2 9.749669 6.686065 9.328821 1.676758   6.860328
3 1.231070 4.339285 9.274955 1.046044   3.972839
cgvoller
  • 873
  • 1
  • 14