user5162881
user5162881

Reputation: 181

Take average between two columns for each row

I want to take the average of two columns by row.

More about the data: I had a bunch of participants come in for a study and I want to take their scores from two different columns, average them, and put them into a new column.

For example, I want this:

Participant #   Score A   Score B   Score C   Score D
1               30.0      32.0      48.2      39.2      
2               43.4      59.3      39.1      78.4
3               92.0      0.90      39.0      87.4

turned into this

    Participant #   Score A   Score B   Score C   Score D   Score A + B Average
    1               30.0      32.0      48.2      39.2      31.00
    2               43.4      59.3      39.1      78.4      51.35
    3               92.0      0.90      39.0      87.4      46.45

Thank you.

Upvotes: 1

Views: 5552

Answers (3)

akrun
akrun

Reputation: 887118

Posting my comment as an answer.

df$scrAB_means <- (df[["Score A"]] + df[[["Score B"]])/2

Upvotes: 4

Cyrus Mohammadian
Cyrus Mohammadian

Reputation: 5193

You can also do the following:

 data$meanAB<-(data$scoreA+data$scoreB)/2

Or w/ dplyr

data<-data%>%
   group_by(participant)%>%
   mutate(meanAB=(scoreA+scoreB)/2)

Upvotes: 1

IRTFM
IRTFM

Reputation: 263342

If the names of the columns for which a mean is desired are given by a character named clnames then try this:

clnames <- c("A","B")
dfrm$scrAM_means <- rowMeans ( dfrm[clnames] )

Upvotes: 4

Related Questions