【问题标题】:R add column that sums the mean of three scores [duplicate]R添加将三个分数的平均值相加的列[重复]
【发布时间】:2021-03-27 15:12:24
【问题描述】:

我有这个data.frame:

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

我想添加一个这样的列:

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

如何在 R 中做到这一点?我如何为任何功能在行上工作。现在,我的意思是。

【问题讨论】:

  • 我已经更新了我的答案。我想要一个更通才的方式
  • @Cettt 抱歉,更新了

标签: r dataframe


【解决方案1】:

你可以从dplyr使用rowwise

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

或者你可以使用 Akrun 的解决方案,类似但更快:

df %>% 
  mutate(fin_mean = select(., scoreA:scoreC) %>% rowMeans)`)

【讨论】:

  • 就是这样!谢谢
【解决方案2】:

如 cmets 中所述,一种非常简单的方法是:

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

或者只是df$finalmean &lt;- rowMeans(df)

【讨论】:

  • 为什么不rowMeans
  • @thela,我正在编辑它:-p
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-13
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
相关资源
最近更新 更多