-1

I want to iterate over two columns of a data frame, calculate the mean if values in both columns exist and if not just use the value that exists in either columns. Here is a dummy example of a much bigger datasets!

  dummy <- data.frame(
  name = c("A", "B", "C" , "D"),
  x = c(66, 80, NA, 23),
  y = c(56, 90, 50, NA))

I want the output to look like this:

     name  x  y Mean
1    A 66 56 61
2    B 80 90 85
3    C NA 50 50
4    D 23 NA 23
Mohere
  • 45
  • 5

1 Answers1

0

I would use the dplyr package to do this. Please also tell us what you tried!

Also a duplicate question can be found here: R dplyr rowwise mean or min and other methods?

dummy_2 <- dummy %>% 
  rowwise() %>% 
  mutate(Mean = mean(c(x,y),na.rm=TRUE))
Community
  • 1
  • 1
Sahir Moosvi
  • 549
  • 2
  • 21