如何使用R dplyr获取多个列值的平均值

时间:2019-07-13 02:38:39

标签: r dplyr mean

(我是一名试图学习R的SAS程序员)。

我有多个数字列。我想使用dplyr来获取每行中多个值的平均值。在SAS中,应为:

newvariable = mean(of x1, x2, x3, x4, x5);

我想像它在R中看起来像这样,但是它只会生成一条错误消息。

代码:

time1data %>%
  mutate(newvariable = mean(of x1, x2, x3, x4, x5)) %>%
  head

1 个答案:

答案 0 :(得分:2)

library(dplyr)
library(tidyr)

# convert to a data frame if not already.
data_frame <- as.data.frame(your_data)

# These are the columns I used for testing for data with five columns
# and are to help you understand the next line of code.
colnames(dataframe) <- c("First", "Second", "Third", "Forth", "Fifth")

# tidyverse gather() via install.packages("tidyverse")
# index is the name of the "key" column, "Group_Mean" of value column
# Kept the convert = True otherwise, they become factor or strings
df.gather.col <- gather(data_frame, key="index", value="Group_Mean",
                        First, Second, Third, Forth, Fifth, 
                        convert=True)

#just prints it out.      
 df.gather.col 

进一步阅读R gather usage,最重要的是,希望对您有所帮助。

相关问题