foboss
foboss

Reputation: 440

replace data frame values in R with double conditions

I have this data frame :

 A  B     C      D
 1  cola  light  0
 2  cola  light  0
 3  cola  lemon  0
 4  Pepsi lemon  0
 5  Pepsi lemon  0

I would like to do a double conditions into "B" and "C" and put the result in D, for example (pseudo code) :

 if B=="cola" and C=="light"
  D=10 else D=20

In R I used ifelse to do it ,but my problem is that B="Cola" or c="light" are always FALSE, i am java user and comparing strings or characters is more easier, I use (equals or compareTo). But in R i don't know how to handle this kind of problem, I tried as.character to transform it but no result. My conditions still retuning False.

Thank you for your help

Upvotes: 1

Views: 319

Answers (3)

akrun
akrun

Reputation: 886938

Or

 dat$D <- c(20,10)[(dat$B=="cola" & dat$C=="light")+1]
dat$D
#[1] 10 10 20 20 20

Data

dat <- structure(list(A = 1:5, B = c("cola", "cola", "cola", "Pepsi", 
"Pepsi"), C = c("light", "light", "lemon", "lemon", "lemon"), 
D = c(0L, 0L, 0L, 0L, 0L)), .Names = c("A", "B", "C", "D"
), class = "data.frame", row.names = c(NA, -5L))

Update

If your dataset columns are:

 dat$B <- c( " cola ", " cola", "cola ", "Pepsi", "Pepsi")
 c(20,10)[(dat$B=="cola" & dat$C=="light")+1]
 #[1] 20 20 20 20 20

In that case,

  c(20,10)[(grepl("cola", dat$B)&grepl("light", dat$C)) +1]
 #[1] 10 10 20 20 20

Or you could use str_trim

library(stringr)

dat[,2:3] <- lapply(dat[,2:3], str_trim) 
c(20,10)[(dat$B=="cola" & dat$C=="light")+1]
 #[1] 10 10 20 20 20

Upvotes: 2

useR
useR

Reputation: 3082

A <- 1:5
B <- c(rep("cola",3), rep("Pepsi", 2))
C <- c(rep("light",2), rep("lemon", 3))
D <- rep(0,5)

Then i have the data.frame exactly like yours

> data
  A     B     C D
1 1  cola light 0
2 2  cola light 0
3 3  cola lemon 0
4 4 Pepsi lemon 0
5 5 Pepsi lemon 0

according to @zx8754

> data$D <- ifelse(data$B=="cola" & data$C=="light", 10,20)
> data
  A     B     C  D
1 1  cola light 10
2 2  cola light 10
3 3  cola lemon 20
4 4 Pepsi lemon 20
5 5 Pepsi lemon 20

Upvotes: 1

zx8754
zx8754

Reputation: 56004

This should work:

df$D <- ifelse(df$B == "cola" & df$C == "light", 10, 20)

Upvotes: 1

Related Questions