A year ago, I created new variables (new1 & new2) with the ifelse statement in R:
data$new1<-ifelse(data$v1==1||data$v2==1||data$v3==1||data$v4==1,1,0)
data$new2<-ifelse(data$varx==307||data$varx==301||data$varx==309||data$varx==321,1,0)
Both statements turned out ok. To my surprise, neither of the two is working any longer since a few weeks... Do you have any idea what might have changed and even better - do you know an alternative function that performs the same calculation?
Thanks for any ideas !
Alternative apporach for the first ifelse
would be to select the columns of interest, do a comparison ( ==
) with 1, get the rowSums
and check if it is greater than 0, then convert the logical vector to binary ( +
)
+(rowSums(data[c('v1', 'v2', 'v3','v4')] == 1) > 0)
Or with Reduce
, loop over the subset of column, convert to a list
of logical vectors by looping over the list
with lapply
and doing the comparison, then Reduce
to a single logical vector with |
, and coerce to binary as before
+(Reduce(`|`, lapply(data[c('v1', 'v2', 'v3', 'v4')] `==`, 1)))
For the second case, it would be comparing one column with a vector of values. So, use %in%
+(data$varx %in% c(307, 301, 309, 321))
You can do it like
setToOneCondition <- data$v1==1 | data$v2==1 | data$v3==1 |data$v4==1
data$new1 <- as.numeric(setToOneCondition)
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.