Reputation: 49
I want to create a new variable "influence" in my dataset (f) based on several conditions taking into account other variables. Here is my code:
f$influence <- if (f$ApportLysine_gj <= f$LysBesoinPlus5 & f$ApportLysine_gj >= f$LysBesoinMoins5){
f$influence = 1
} else if (f$ApportLysine_gj > f$LysBesoinPlus5 & f$ApportLysine_gj < f$LysExces20){
f$influence = 2
} else if (f$ApportLysine_gj >= f$LysExces20) {
f$influence = 3
} else if (f$ApportLysine_gj < f$LysBesoinMoins5 & f$ApportLysine_gj > f$LysDeficit20){
f$influence = 4
} else {
f$influence = 5}
I only get an error message "argument is of length zero". What am I doing wrong?
Upvotes: 0
Views: 36
Reputation: 76402
You can try using a logical index and assigning the values of the new variable according to its value.
f$influence <- 5
i <- f$ApportLysine_gj <= f$LysBesoinPlus5 & f$ApportLysine_gj >= f$LysBesoinMoins5
f$influence[i] <- 1
i <- f$ApportLysine_gj > f$LysBesoinPlus5 & f$ApportLysine_gj < f$LysExces20
f$influence[i] <- 2
i <- f$ApportLysine_gj >= f$LysExces20
f$influence[i] <- 3
i <- f$ApportLysine_gj < f$LysBesoinMoins5 & f$ApportLysine_gj > f$LysDeficit20
f$influence[i] <- 4
Upvotes: 1
Reputation: 8110
I often find that if I have lots of if
, else if
, or ifelse
in coding a variable, dplyr
's case_when
is very handy. Please see below, keep in mind that I couldn't test this without having your data.
library(dplyr)
f %>%
mutate(influence = case_when(
ApportLysine_gj <= LysBesoinPlus5 & ApportLysine_gj >= LysBesoinMoins5 ~ 1,
ApportLysine_gj > LysBesoinPlus5 & ApportLysine_gj < LysExces20 ~ 2,
ApportLysine_gj >= LysExces20 ~ 3,
ApportLysine_gj < LysBesoinMoins5 & ApportLysine_gj > LysDeficit20 ~ 4,
TRUE ~ 5
))
Upvotes: 3