nomi
nomi

Reputation: 91

replace values in a column into Data Frame with another value (same for all)

My data frame consists of 21 columns, for this problem only one is relevant: I want replace values 2 or 3 or 4 or 5 in a column a with the value 1 (in the same column).

beside of doing the code below for any value 2,3,4,5 i'm looking for something more elegant:

  df <- df %>% mutate (a = replace(a, a == 2,1))
  df <- df %>% mutate (a = replace(a, a == 3,1))
  df <- df %>% mutate (a = replace(a, a == 4,1))
  df <- df %>% mutate (a = replace(a, a == 5,1))

so i'm just stock with the condition "or" i need create inside the code... any solution?

Upvotes: 0

Views: 87

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You can replace multiple columns using across and multiple values with %in%. For example, if you want to replace values from column a, b, c and d, you can do :

library(dplyr)
df <- df %>% mutate(across(a:d, ~replace(., . %in% 2:5, 1)))
#For dplyr < 1.0.0 use `mutate_at`
#df <- df %>% mutate_at(vars(a:d), ~replace(., . %in% 2:5, 1))

In base R, you can do this with lapply :

cols <- c('a','b','c','d')
df[cols] <- lapply(df[cols], function(x) replace(x, x %in% 2:5, 1))

Upvotes: 1

Related Questions