Home > Back-end >  How to replace a value by function in R using mutate?
How to replace a value by function in R using mutate?

Time:12-08

How do I change a value in a column for a specific condition by a calculation? So I want to divide by 7 for some of the values in a particular column. It is not possible for me to share data or codes. But my question is almost exactly like this previous question Replace values in multiple columns by values of another column on condition someone answered the question (named camnesia) with this code:

library(dplyr)

df <- df %>%
  mutate(var2 = case_when(var1 %in% c('02','03') ~ '0',
                          TRUE ~ as.character(var2)),
         var3 = case_when(var1 %in% c('02','03') ~ '00',
                          TRUE ~ as.character(var3)),
         var4 = case_when(var1 %in% c('02','03') ~ '000',
                          TRUE ~ as.character(var4)))

I tried to run the code for my data like this:

library(dplyr)

df <- df %>%
  mutate(var1 = case_when(var2 %in% c('A') ~ ./7,
                          TRUE ~ as.character(var1)))

I want to change the values in var1 that belongs to group 'A' (groups are defined in var2 column), by dividing the values with 7? How do I add that calculation to the above code? Because it does not work like this for me.

Thanks a lot in advance! :)

CodePudding user response:

You need to have consistent type for column var1. In your code you mix numerical with text. You should encompass the division in as.character() This should work, assuming var1 was numerical:

library(dplyr)

df <- df %>%
  mutate(var1 = case_when(var2 %in% c('A') ~ as.character(var1/7),
                          TRUE ~ as.character(var1)))

If var1 was character at start, then:

library(dplyr)

df <- df %>%
  mutate(var1 = case_when(var2 %in% c('A') ~ as.character(as.double(var1)/7),
                          TRUE ~ as.character(var1)))

CodePudding user response:

R dplyr mutate() – Replace Column Values. Use mutate() and its other verbs mutate_all() , mutate_if() and mutate_at() from R dplyr package to replace/update the values of the column (string, integer, or any type) in DataFrame (data. frame). For more methods of this package refer to the R dplyr tutorial.

  • Related