重复一个动作,直到满足条件

时间:2014-03-25 09:46:50

标签: r

我在这里有这张表。

它被称为d,结果是:

                  V1       V2       V3       V4         V5   V6           V7        V8
1    testtest_no_2nd  14.06863 11.50424 333173.1        0.0  0.00000      NaN       0.00
2    testtest1_no_2nd 14.50265 11.89501 387709.7    54536.6  0.43402 125654.6        NaN
3    testtest2        14.55234 11.95746 402124.0    14414.3  0.04969 290084.5  164429.95
4    testtest3        14.78606 12.14149 453059.3    50935.3  0.23372 217933.0  -72151.53
5    testtest4        15.16970 12.51004 496142.1    43082.8  0.38364 112300.1 -105632.92

我需要的是首先我需要将Nan值转换为0然后我需要删除V8 Vector的第一个元素并在末尾添加0值。我现在就是

V8
0.00
164429.95
-72151.53
-105632.92

之后,我需要删除具有V8< 0

的d表的所有行

有人帮我这个吗? 感谢。

1 个答案:

答案 0 :(得分:0)

使用矩阵更容易,但要使用data.frame,请尝试以下操作:

d.new <- do.call(cbind.data.frame, lapply(d, function(x) {
  x[is.nan(x)] <- 0
  x
}))

d.new['V8'] <- c(d.new[-1, 'V8'], 0)

subset(d.new, V8 >= 0)

                V1       V2       V3       V4      V5      V6       V7     V8
1  testtest_no_2nd 14.06863 11.50424 333173.1     0.0 0.00000      0.0      0
2 testtest1_no_2nd 14.50265 11.89501 387709.7 54536.6 0.43402 125654.6 164430
5        testtest4 15.16970 12.51004 496142.1 43082.8 0.38364 112300.1      0

现在,如果d是col1为row.names的矩阵,那么它会更简单一些:

m <- as.matrix(d[, -1])
row.names(m) <- d[, 1]
m[is.na(m)] <- 0
m[m[, 'V8'] >= 0, ]
相关问题