1
votes

I have a dataframe ("daily") simplified as follow:

Day Spot
1 1
1 2
1 3
1 4
1 5
1 6

I want a new column, treatment, whose elements should be factors "ambient" (spots 2,3,6) and "elevated" (spots 1, 4, 5). I have tried this:

daily$treatment<- factor(ifelse(daily$ring==c("1","4","5"), "elevated", "ambient"))  

But it returned this warnings, and the result is not what I need: Warning messages: 1: In is.na(e1) | is.na(e2) : longer object length is not a multiple of shorter object length 2: In ==.default(daily$ring, c("1", "4", "5")) : longer object length is not a multiple of shorter object length Alternatively I have also tried, but nothing:

if (daily$ring==1 | daily$ring==4 | daily$ring==5){
   daily$treatment <- "elevated"
 } else {
   daily$treatment <- "ambient"
 }  

What am I doing wrong? Thanks

1
You are looking for %in%... - mnel
Also, the problem with your second snippet of code is that if and else are not vectorized (you would have to do for(i in 1:nrow(daily))... if you wanted that version to work). - Señor O

1 Answers

2
votes
daily$treatment <- factor(ifelse(daily$Spot %in% c(1,4,5), "elevated", "ambient"))

daily
##   Day Spot treatment
## 1   1    1  elevated
## 2   1    2   ambient
## 3   1    3   ambient
## 4   1    4  elevated
## 5   1    5  elevated
## 6   1    6   ambient