Cbind/Rbind With Ifelse Condition

非 Y 不嫁゛ 提交于 2019-12-01 23:09:30

问题


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.


回答1:


Try

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

Or

 `row.names<-`(t(t(rbind(y,z))[,(x!='Yes')+1L]),x)


来源:https://stackoverflow.com/questions/31542285/cbind-rbind-with-ifelse-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!