1

I want to reassign multiple different character strings with the same value in a single call. However, the following code only replaces some of values in each variable.


dat <-data.frame(x=c(rep("1=x",4),rep("b",4)),y=c(rep("1=z",4),rep("b",4)))
dat[] <- sapply(dat[], as.character)
dat[dat == c("1=x", "1=y")]<- 1

such that I get:

dat  
x   y
1   1 1=z
2 1=x 1=z
3   1 1=z
4 1=x 1=z
5   b   b
6   b   b
7   b   b
8   b   b

when I want is the following:

dat  
x   y
1   1   1
2   1   1
3   1   1
4   1   1
5   b   b
6   b   b
7   b   b
8   b   b
0

2 Answers 2

1

With dplyr:

library(dplyr)

dat <- mutate_all(dat, funs(replace(., grepl("1=", .), 1)))

With Base R:

dat[] <- lapply(dat, function(x) replace(x, grepl("1=", x), 1))

Result:

  x y
1 1 1
2 1 1
3 1 1
4 1 1
5 b b
6 b b
7 b b
8 b b

Data:

dat <- structure(list(x = c("1=x", "1=x", "1=x", "1=x", "b", "b", "b", 
"b"), y = c("1=z", "1=z", "1=z", "1=z", "b", "b", "b", "b")), .Names = c("x", 
"y"), row.names = c(NA, -8L), class = "data.frame")
Sign up to request clarification or add additional context in comments.

Comments

0

Another Base R option if you want to make an explicit replacement of certain strings would be:

dat[] <- lapply(dat,function(x) ifelse(x %in% c("1=x", "1=z"), 1, x))

Result:

  x y
  1 1 1
  2 1 1
  3 1 1
  4 1 1
  5 b b
  6 b b
  7 b b
  8 b b

Data:

dat <- structure(list(x = c("1", "1", "1", "1", "b", "b", "b", "b"), 
y = c("1", "1", "1", "1", "b", "b", "b", "b")), row.names = c(NA, 
-8L), class = "data.frame")

Comments

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.