Mean of Multiple Columns in R

本秂侑毒 提交于 2019-12-11 06:37:58

问题


I am trying take the mean of a list of columns in R and am running into a issue. Let's say I have:

A B  C  D
1 2  3  4
5 6  7  8
9 10 11 12

What I am trying to do is take the mean of columns c(A,C) and save it as a value say (E) as well as the mean of columns c(B,D) and have it save as a different value say F. Is that possible?

E   F
2   3
6   7
10  11

回答1:


Check out dplyr:

library(dplyr)
df <- df %>% mutate(E=(A+C)/2, F=(B+D)/2)
df

  A  B  C  D  E  F
1 1  2  3  4  2  3
2 5  6  7  8  6  7
3 9 10 11 12 10 11



回答2:


We can subset the dataset with columns 1 & 2, another one with 3 & 4, add them together, divide by 2, and change the column names with setNames

setNames((df1[1:2] + df1[3:4])/2, c("E", "F"))
#   E  F
#1  2  3
#2  6  7
#3 10 11

Or another option is rowMeans by keeping it in a list using the recycling logical vector, loop through the list (using sapply) and get the rowMeans

i1 <- c(TRUE, FALSE)
sapply(list(df1[i1], df1[!i1]), rowMeans)

Or another option is unlist the dataset, convert it to array and use apply to get the mean

apply(array(unlist(df1), c(3, 2, 2)), c(1,2), mean)


来源:https://stackoverflow.com/questions/41962554/mean-of-multiple-columns-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!