Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new column based on two other columns, but average when observed in both

Tags:

r

dplyr

I have two numeric columns score.a and score.b. I want to create a new variables score.c that transfers the observed score from a or b, but when they are observed in both, I need to take the average.

help <- data.frame(deid = c(5, 7, 12, 15, 25, 32, 42, 77, 92, 100, 112, 113),
               score.a = c(NA, 2, 2, 2, NA, NA, NA, NA, NA, NA, 2, NA),
               score.b = c(4, NA, NA, 4, 4, 4, NA, NA, 4, 4, NA, 4))

creates

    deid score.a score.b
1     5      NA       4
2     7       2      NA
3    12       2      NA
4    15       2       4
5    25      NA       4
6    32      NA       4
7    42      NA      NA
8    77      NA      NA
9    92      NA       4
10  100      NA       4
11  112       2      NA
12  113      NA       4

And I am hoping to create a df that looks like

     deid score.a score.b score.c
1     5      NA       4     4
2     7       2      NA     2
3    12       2      NA     2
4    15       2       4     3
5    25      NA       4     4
6    32      NA       4     4
7    42      NA      NA     NA
8    77      NA      NA     NA
9    92      NA       4     4
10  100      NA       4     4
11  112       2      NA     2
12  113      NA       4     4

for example, in row 4 it takes the mean.

My attempt used help %>% group_by(deid) %>% mutate(score.c = (score.a + score.b)/2) but this only handled the data observed in both columns.

like image 297
b222 Avatar asked Jun 16 '15 04:06

b222


2 Answers

A data.table solution would be:

library(data.table)
setDT(help)
help[,.(rMean=rowMeans(.SD,na.rm = T)),.SDcols = c('score.a','score.b')]
like image 156
hvollmeier Avatar answered Sep 27 '22 15:09

hvollmeier


Try

  help$score.c <- rowMeans(help[2:3], na.rm=TRUE)

Or a possible approach with dplyr (not tested thoroughly)

 library(dplyr)
 help %>%
     mutate(val= (pmax(score.a, score.b, na.rm=TRUE)+
                  pmin(score.a, score.b, na.rm=TRUE))/2)
like image 31
akrun Avatar answered Sep 27 '22 17:09

akrun