Cbind / Rbind With Ifelse Condition
Here is the code I am working with:
x <- c("Yes","No","No","Yes","Maybe")
y <- t(1:10)
z <- t(11:20)
rbind.data.frame(ifelse(x == "Yes",y,z))
This creates
X1L X12L X13L X4L X15L
1 1 12 13 4 15
Desired output:
x
1 Yes 1 2 3 4 5 6 7 8 9 10
2 No 11 12 13 14 15 16 17 18 19 20
3 No 11 12 13 14 15 16 17 18 19 20
4 Yes 1 2 3 4 5 6 7 8 9 10
5 Maybe 11 12 13 14 15 16 17 18 19 20
I thought I could use an ifelse statement with rbind.data.frame () or cbind.data.frame () function. Therefore, if x == "Yes"
, then it will be combined with the vector "y". As shown in the first line of the desired output. Conversely, if x!="Yes"
, then it will be combined with the vector "z". How would I do it. I also thought that indexing with the () function might be possible, but I couldn't think of how I would use it.
UPDATE ANOTHER QUESTION
Here is the code I am working with:
a <- c(1,0,1,0,0,0,0)
b <- 1:7
t(sapply(a, function(test) if(test==0) b else 0))
Which produces
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 0 Integer,7 0 Integer,7 Integer,7 Integer,7 Integer,7
Can any of you explain this? The code below works, but I was wondering why the sapply function was not working. Also how to save the matrix created below?
`row.names<-`(t(t(rbind(b,0))[,(a!='1')+1L]),x)
The answer to my last question
For the sapply function to work, you need a vector to enter the else statement, so
a <- c(1,0,1,0,0,0,0)
b <- 1:7
c <- rep(0, times = length(a))
t(sapply(a, function(test) if(test==0) b else c))
This now gives the correct conclusion.
source to share