Dante Smith
Dante Smith

Reputation: 591

Mean of Multiple Columns in R

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

Upvotes: 1

Views: 4166

Answers (2)

thc
thc

Reputation: 9705

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

Upvotes: 3

akrun
akrun

Reputation: 887961

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)

Upvotes: 2

Related Questions