Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutate data conditionally in dplyr

Tags:

r

dplyr

I am trying to mutate data by dividing based on an identifier. For example, I would like to mutate mass in the following data. If it is depth 10, I would like to divide by 2. If it is depth 20, I would like to divide by 3.

day    year    depth    mass 
1      2008    10       13
2      2008    10       15
1      2008    20       14
2      2008    20       12
1      2009    10       14
2      2009    10       16
1      2009    20       12
2      2009    20       18   

Division leads to:

day    year    depth    mass 
1      2008    10      6.5
1      2008    10      6.5
2      2008    10      7.5
2      2008    10      7.5
1      2008    20      4.6
1      2008    20      4.6
2      2008    20      4
2      2008    20      4
1      2009    10      7
1      2009    10      7
2      2009    10      8
2      2009    10      8   
1      2009    20      4
1      2009    20      4  
2      2009    20      6 
2      2009    20      6  

I am trying ifelse in the following way, but get an error "unused arguments(c(13, 15, 14. . .)"

df%>% 
  group_by(day, year, depth) %>% 
  bind_rows(., .) %>%
  mutate(mass = ifelse(depth == 10), mass/2,
         ifelse(depth == 20), mass/3)%>%
  arrange(day, year, depth, mass)
like image 382
Nazer Avatar asked Jan 06 '16 21:01

Nazer


1 Answers

I see two errors in your use of ifelse. where you have ifelse(depth == 10), you've only given ifelse one argument where it needs three. Remove the closing parenthesis and you have a good start.

Your second error is that you didn't give any indication of what to do if the second ifelse condition resolves to FALSE. In the code below, I've assigned NA to that situation. I'm not sure if that's the behavior you want, however, so you should change it to what fits your needs.

df%>% 
  group_by(day, year, depth) %>% 
  bind_rows(., .) %>%
  mutate(mass = ifelse(test = (depth == 10), 
                       yes = mass/2,
                       no = ifelse(test = (depth == 20), 
                                   yes = mass/3,
                                   no = NA))) %>%
  arrange(day, year, depth, mass)
like image 164
Benjamin Avatar answered Oct 03 '22 13:10

Benjamin