Mutant data conditionally in dplyr

I am trying to mutate data by dividing based on identifier. For example, I would like to mutate massin the following data. If it is a depth of 10, I would like to divide by 2. If it is a depth of 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   

The department 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 try to use it ifelseas follows, but I get the error message "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)
+4
source share
3 answers

I see two errors when using ifelse. where you have ifelse(depth == 10), you have indicated only ifelseone argument, where he needs three. Remove the closing bracket and you have a good start.

, , , ifelse FALSE. NA . , , , , , .

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)
+6

:

ifelse(test, yes, no)

:

ifelse(depth == 10, mass/2, ifelse(depth == 20, mass/3 , mass))
+4

The Modulo operator works well here.

df %>%
    mutate(mass = mass *
        as.integer(!(depth %% 10)) * 1 / 2 +
        as.integer(!(depth %% 20)) * 1 / 3 
    ) %>%
arrange(day, year, depth, mass)

# let underscore _ denote previous line result
# depth %% 10   ---> remainder left over after modulus division
# !(_)          ---> coerce integer to logical and negate 
# as.integer(_) ---> coerce back to integer for arithmetic operations
0
source

Source: https://habr.com/ru/post/1623159/


All Articles