r根据条件选择列元素

时间:2013-05-24 13:32:47

标签: r select

> w
                 A           B
1998-01-08 -0.0051653999  0.007
1998-01-09  0.0064191599 -0.008
1998-01-12 -0.0018169993  0.009
1998-01-13  0.0046482541 -0.005
1998-01-14  0.0080997329 -0.006
1998-01-15 -0.0007764179  0.008

c<-(-0.5,-0.6,-0.7,0.1,0.2,0.3)

我想创建一个矩阵,其中一列从w中选择A或B,条件是c> 0

w[,if (c<0) A else B]
                 C           
1998-01-08 -0.0051653999
1998-01-09  0.0064191599
1998-01-12 -0.0018169993
1998-01-13 -0.005
1998-01-14 -0.006
1998-01-15  0.008

2 个答案:

答案 0 :(得分:1)

您错过c功能以连接向量(-0.5,-0.6,-0.7,0.1,0.2,0.3),我使用ind作为该向量的名称。然后可以使用ifelse函数完成索引,如下所示:

> ind <-c(-0.5,-0.6,-0.7,0.1,0.2,0.3)
> data.frame(C=ifelse(ind<0, w$A, w$B), row.names=rownames(w))
                      C
1998-01-08 -0.005165400
1998-01-09  0.006419160
1998-01-12 -0.001816999
1998-01-13 -0.005000000
1998-01-14 -0.006000000
1998-01-15  0.008000000

答案 1 :(得分:0)

试着看看Extract matrix column values by matrix column name 简而言之,我想你想尝试这个命令: 如果(C&小于0) W [, “A”] 其他 W [, “B”]