3

Here is the code that 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 produces

    X1L X12L X13L X4L X15L
1   1   12   13   4   15

The desired outcome is:

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 was thinking that I could use an ifelse statement with the rbind.data.frame() or cbind.data.frame() function. So if x == "Yes" then that would be combined with a vector "y". As shown in the first row of the desired output. Inversely if x!="Yes" then it would be combinded with the vector "z". How would I go about doing this. I also thought maybe indexing with the which() function could be possible but I could not 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 does not work. Also how would I save the matrix that is created below?

`row.names<-`(t(t(rbind(b,0))[,(a!='1')+1L]),x) 

Answer To My Most Recent Question

For the sapply function to work it needs the input in the else statement to be a vector 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))

Now this produces the proper output.

10 Rep
  • 2,217
  • 7
  • 19
  • 33
Adam Warner
  • 1,334
  • 2
  • 14
  • 30

1 Answers1

5

Try

 t(sapply(x, function(x) if(x=='Yes') y else z))

Or

 `row.names<-`(t(t(rbind(y,z))[,(x!='Yes')+1L]),x)
akrun
  • 874,273
  • 37
  • 540
  • 662