user1737940
user1737940

Reputation: 1

Adding columns with condition check on row name

I am having troubles adding column conditionally to a df. For instance, I would like to add class values to column VarB and VarC according to the value of Var A.

For instance, I would like to add 'yes' to VarB when VarA equals "a", "c" and "e" and "no" when it equals "b" and "d". Also, I would like to add "1" to VarC when VarA equals "a" or "e"; "2" to VarC when VarA equals "b" or "d"; and, "3" to VarC when VarA equals "c".

VarA
 a     
 b     
 c     
 d     
 e 

Any tips?

Upvotes: 0

Views: 158

Answers (2)

Jilber Urbina
Jilber Urbina

Reputation: 61214

Maybe this could be useful

DF <- data.frame(VarA=letters[1:4]) # this is your data.frame
    VarA
1    a
2    b
3    c
4    d

DF$VarB <- ifelse(VarA %in% c('a','c','e'), 'yes', 'no')
DF$VarC <- ifelse(VarA %in% c('a','e'), 1, ifelse(VarA %in% c('b','d'),2,3))
DF
  VarA VarB VarC
1    a  yes    1
2    b   no    2
3    c  yes    3
4    d   no    2

You can use transform function as well.

DF <- data.frame(VarA=letters[1:4])
transform(DF, 
          VarB=ifelse(VarA %in% c('a','c','e'), 'yes', 'no'), 
          VarC=ifelse(VarA %in% c('a','e'), 1, ifelse(VarA %in% c('b','d'),2,3)))
  VarA VarB VarC
1    a  yes    1
2    b   no    2
3    c  yes    3
4    d   no    2

Upvotes: 3

mpiktas
mpiktas

Reputation: 11518

Do something in the spirit of the following:

cond1 <- data$VarA %in% c("a","c","e")
data$VarB[cond1] <- "yes"
cond2 <- data$VarA %in% c("b","d")
data$VarB[cond2] <- "no"
cond3 <- data$VarA %in% c("a","e")
data$VarC[cond3] <- 1
cond4 <- data$VarA %in% c("b","d")
data$VarC[cond4] <- 2

And I'll leave you to do the the last one yourself.

Upvotes: 1

Related Questions