Worice
Worice

Reputation: 4047

Adding conditional attributes to data.frame

I hope the question is posted correctly. A similar problem is faced here, even if it is slightly different about the expected result. I would like to create a 20 rows dataframe with 10 men and 10 women:

e6 <- data.frame(20)
e6 <- rep( c("man", "woman"), c(10, 10))
e6
[1] "man"   "man"   "man"   "man"   "man"   "man"   "man"   "man"  
[9] "man"   "man"   "woman" "woman" "woman" "woman" "woman" "woman"
[17] "woman" "woman" "woman" "woman" 

Now I would like to create a column e6$answer where between the 10 men, 8 of them say "yes" and 2 of them "no". Between the 10 women: 3 of them say "yes" and 7 of them say "yes". I tried using the approach suggested at the link at the top of the post:

e6$answer <- ifelse(e6 == "man", rep( c("yes", "no"), c(8, 2)), 
             rep( c("yes", "no"), c(3, 7)))

Unfortunately, my attempt returns an error. Probably I am doing an error with the classes.

Warning message:
In e6$answer <- ifelse(e6 == "man", rep(c("yes", "no"), c(8, 2)),  :
  Coercing LHS to a list

Thank you very much for your patience.

Upvotes: 0

Views: 165

Answers (1)

lukeA
lukeA

Reputation: 54277

In your example, e6 is a character vector (see class(e6)), not a data frame. Thus, ifelse coerces it to a list. Try

e6 <- data.frame(gender = rep( c("man", "woman"), each=10))
e6$answer <- ifelse(e6 == "man", rep( c("yes", "no"), c(8, 2)), 
             rep( c("yes", "no"), c(3, 7)))

Upvotes: 2

Related Questions