简体   繁体   中英

R function to assign value based on multiple columns

I have a function that assigns a value (cat, dog or rabbit) to column c of a dataframe based on the entry in column b:

mydf <- data.frame(a = c(1:4), b= c(1,3,5,9))
myfunction <- function(x) { 
if(x == 1 | x == 2) y <- "cat"
if(x > 2 & x < 6) y <- "dog"
if(x > 6) y <- "rabbit"
return(y)
 }
mydf$c <- sapply(mydf$b,myfunction)

Now I would like to write a function that makes the assignment conditional on the values of columns a AND b. So for example, the conditions might be: A: cat is assigned if and only if mydf$a == 1 & mydf$b == 1; B: dog is assigned whenever mydf$a == 2 regardless of the value of mydf$b, and also when mydf$a == 3 & mydf$b == 5; C: rabbit is assigned for the other cases. Having some trouble with the syntax, could not find an example from previous post.

You could try ifelse

 indx <- as.character(interaction(mydf,sep=""))
 mydf$c <- ifelse(indx=='11', 'cat', 
       ifelse(substr(indx,1,1)=='2'|indx=='35', 'dog', 'rabbit')) 

 mydf
 #  a b      c
 #1 1 1    cat
 #2 2 3    dog
 #3 3 5    dog
 #4 4 9 rabbit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM