0

I have this data.frame:

scoreA    scoreB    scoreC
  50        60        70
 ...       ...       ...

I want to add a colum such that:

scoreA    scoreB    scoreC   Final_mean
  50        60        70        60
 ...       ...       ...

How to do that in R? How do I work on row for any function. Now, I have mean.

Cettt
  • 11,460
  • 7
  • 35
  • 58
V_head
  • 17
  • 6

2 Answers2

1

you can use rowwise from dplyr

library(dplyr)

df <- data.frame(scoreA = 50, scoreB = 60, scoreC = 70)

df %>%#
  rowwise() %>%
  mutate(fin_mean = mean(scoreA:scoreC)) %>%
  ungroup()

# A tibble: 1 x 4
  scoreA scoreB scoreC fin_mean
   <dbl>  <dbl>  <dbl>    <dbl>
1     50     60     70       60

Or you can use Akrun's solution, which is similar but faster:

df %>% 
  mutate(fin_mean = select(., scoreA:scoreC) %>% rowMeans)`)
Cettt
  • 11,460
  • 7
  • 35
  • 58
1

As mentioned in the comments, a pretty straightforward way would be to do:

df$finalmean <- rowSums(df)/ncol(df)
df
##   scoreA scoreB scoreC finalmean
## 1     50     60     70        60

Or just df$finalmean <- rowMeans(df)

A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485