0

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?

0

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

2 Comments

but if i dont have chronological order in my values, how can i write it? such as 3,6,8,2
You can use replace(., . %in% c(3,6,8,2), 1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.