具有Ifelse条件的Cbind / Rbind [英] Cbind/Rbind With Ifelse Condition

查看:154
本文介绍了具有Ifelse条件的Cbind / Rbind的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我正在使用的代码:

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))

这产生

    X1L X12L X13L X4L X15L
1   1   12   13   4   15

期望的结果是:

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

我在想我可以在rbind.data.frame()或cbind.data.frame()函数中使用ifelse语句。因此,如果 x ==是那么它将与向量y组合。如所需输出的第一行所示。反之,如果 x!=是那么它将与向量z组合。我该怎么做呢?我也想过可能使用which()函数进行索引但是我想不出如何使用它。

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.

更新另一个问题

以下是我正在使用的代码:

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

你能解释一下吗?下面的代码有效,但我想知道为什么sapply函数不起作用。另外我如何保存下面创建的矩阵?

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) 

回答我最近的问题

为了使sapply函数正常工作,它需要else语句中的输入为vector,

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.

推荐答案

尝试

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

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

这篇关于具有Ifelse条件的Cbind / Rbind的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆