y$ll<-apply (y,1, function(w) ifelse(sum(w=="d2")==2 || unlist(w) %in% c("d3","d4"),1,0))
didn't give the right result might have a bug
line 11 , 12, and 3
y$ll<-apply (y,1, function(w) ifelse(sum(w=="d2")==2 || unlist(w) %in% c("d3","d4"),1,0))
didn't give the right result might have a bug
line 11 , 12, and 3
Hi
Nope, there is no bug here: ifelse works as expected (see below for line 11). You probably want to use a if () {} else {} construct instead of ifelse which is a vectorized function to evaluate condition.
> w <- rep('d',12)
> w[9] <- 'd4'
> w
[1] "d" "d" "d" "d" "d" "d" "d" "d" "d4" "d" "d" "d"
> ifelse(sum(w=='d2')==2 || unlist(w) %in% c('d3', 'd4'), 1, 0)
[1] 0
> sum(w=='d2')==2
[1] FALSE
> unlist(w) %in% c('d3', 'd4')
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE
> sum(w=='d2')==2 || unlist(w) %in% c('d3', 'd4')
[1] FALSE
Or, if you want to test if any of the elements of w are d3 or d4, use
ifelse(sum(w=='d2')==2 || any(unlist(w) %in% c('d3', 'd4')), 1, 0)
I want to test if any 2 d2 in a row or any d3 or d4 in a row then 1 else 0
Then my suggestion should work.
let me try and i will keep you posted thank you
Right now it doesnt work
here is my errors message
ichierSK$impacted<-apply(fichierSK,1,function(v) ifelse(sum(v=="D2")==2|unlist(v) %in% c("D3","D4")),1,0)
Error in FUN(newX[, i], ...) : unused arguments (1, 0)
The ifelse() function that was suggested by stkrog should be used inside of an apply() function as in your first post. What you have done is test the entire data frame y within the ifelse, which gives unexpected results. You want to test each row of the data frame.
I think we really need a Reproducible Example. What you provided before was just an image. To make a reproducible example, you need to post here the code to make example data and the code used to process that example data set. Making the example data can be done using datapasta or dput as explained under the Minimal Dataset heading of the post linked below. If you cannot do that, just use the data.frame() function and type out your data. The beginning of that process might look like this
y <- data.frame(x1 = c("d", "d1", "d2", "d3", "d4", "d", "d", "d", "dd", "d", "d", "d1"),
x2 = c("d", ...More Typing))
Type out enough rows of data to illustrate your problem, then post that code, the processing code and the observed result. The reprex package will help you make an easily copied post on the forum.
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.