rmutated

How can I extract negative values from an existing column into a new column


I have a dataframe (sy2.1) with a column (Vannstand2.cm) containing both positive and negative values of water level. I want to separate the negative and positive values into two new columns, whilst still keeping the original column. I have tried to mutate the negative values using this code:

sy2.1 %>% 
  group_by(Vannstand2.cm) %>% 
  mutate(Vannstand2_neg=case_when(Vannstand2.cm<0.0))

That didnt work, the error complained about negative values even though I specifically ask to only move everything below 0.0. I have also tried several other codes, but nothing seems to work..

Are there any other codes for this issue?


Solution

  • either use if_else:

    sy2.1 %>% 
      group_by(Vannstand2.cm) %>% 
      mutate(Vannstand2_neg = if_else(Vannstand2.cm < 0.0, 0, NA))
    

    or with case_when

    sy2.1 %>% 
      group_by(Vannstand2.cm) %>% 
      mutate(Vannstand2_neg = case_when(Vannstand2.cm < 0.0 ~ 0))