Katherine Adams
Katherine Adams

Reputation: 13

replacing multiple values in data frame in R

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

Upvotes: 1

Views: 58

Answers (2)

Soeren D.
Soeren D.

Reputation: 352

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")

Upvotes: 0

acylam
acylam

Reputation: 18691

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")

Upvotes: 1

Related Questions