0

可以说,例如,我有以下名为“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.x 中满足的每个条件应用不同的函数。例如:

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

帮助将不胜感激!

4

1 回答 1

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 }
于 2013-05-08T14:55:03.230 回答