为特定数据框中满足的每个条件应用不同的公式

时间:2013-05-08 14:32:06

标签: r dataframe conditional-statements

让我们说例如我有以下数据框叫做“df1”(它实际上是一个更大的数据框的一部分,但这个例子现在会做):

DF1 =

[,1]    [,2]    [,3]
   1    -0.5     1.3
   1    -0.3     0.9
   5    -0.2     0.2
   2     0.4     0.5
   0     0.5     1.1
   2     1.1     0.1
   1    -0.6     1.8

我创造了以下条件:

condA= df1[,2] >= 0 & df2[,3]  > 1
condB= df1[,2] >= 0 & df2[,3] <= 1
condC= df1[,2]  < 0 & df2[,3]  > 1
condD= df1[,2]  < 0 & df2[,3] <= 1

我的问题出现了:

如何为df1中满足的每个条件应用不同的函数。例如:

If condA is met: df1[,1]=df1[,1]*1
If condB is met: df1[,1]=df1[,1]*2
If condC is met: df1[,1]=df1[,1]*3
If condD is met: df1[,1]=df1[,1]*4

考虑到我的例子“df1”,输出数据框将是这样的:

[,1]    [,2]    [,3]
   3    -0.5     1.3      # In this row condC is met
   4    -0.3     0.9      # In this row condD is met
  20    -0.2     0.2      # In this row condD is met
   4     0.4     0.5      # In this row condB is met
   0     0.5     1.1      # In this row condA is met
   4     1.1     0.1      # In this row condB is met
   3    -0.6     1.8      # In this row condC is met

非常感谢帮助!!

1 个答案:

答案 0 :(得分:1)

只需按照上面所写的内容进行操作即可。

condA <- df1[,2] >= 0 & df1[,3]  > 1
df1[condA,1] <- df1[condA,1] * 1

(虽然为了提高效率,你可以跳过这个,因为它没有做任何事情。我也假设你的问题中的df2是一个错字,因为你从来没有提到它。)

让它更简洁的一种方法可能就是根据你的条件制作清单然后循环。

conds <- list(
condA= df1[,2] >= 0 & df1[,3]  > 1,
condB= df1[,2] >= 0 & df1[,3] <= 1,
condC= df1[,2]  < 0 & df1[,3]  > 1,
condD= df1[,2]  < 0 & df1[,3] <= 1)
for(i in 1:4) { df1[conds[[i]],1] <- df1[conds[[i]],1] * i }