0

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?

1
  • Put your code, it will help to help you Commented Oct 11, 2012 at 13:09

2 Answers 2

3

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

1 Comment

Perfect use of transform() ;)
1

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.

2 Comments

You can avoid cond2 and cond4 if you just do !cond1 and !cond3, respectively. e.g. data$VarB[!cond1] <- "no"
Well yeah, but I assumed this as a general question, i.e. the nice property you mention might be only a coincidence.

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.