计算跨行间隔之间的值

时间:2018-01-27 09:22:10

标签: r statistics sum

我已经df

set.seed(007)
x <- data.frame(v1=sample (1:100, 50), 
                v2=sample (1:100, 50), 
                v3=sample (1:100, 50),
                v4=sample (1:100, 50),
                v5=sample (1:100, 50))

我需要计算这些间隔之间的行(v1:v5)的值:<25; 25-49; 50-74; >=75。 我尝试过:

x$less.25 <- rowSums(x < 25, na.rm=TRUE)
x$between.25_49 <- rowSums(x >= 25 & x < 50, na.rm=TRUE)
x$between.50_74 <- rowSums(x >= 50 & x < 75, na.rm=TRUE)
x$greater.75 <- rowSums(x >= 75, na.rm=TRUE) 

1 个答案:

答案 0 :(得分:1)

如果我已正确理解您的问题:

x$less.25 <- apply(x, 1, function(x){sum(x < 25)})
x$between.25_49 <- apply(x, 1, function(x){sum(x >= 25 & x <50)})
x$between.50_74 <- apply(x, 1, function(x){sum(x >= 50 & x <75)})
x$greater.75 <- apply(x, 1, function(x){sum(x >= 75)})

这给出了

   v1 v2  v3 v4 v5 less.25 between.25_49 between.50_74 greater.75
1  99 58  40 10 70       1             1             2          1
2  40 72  49 90 87       0             2             1          2
3  12 76  99 19 71       2             0             1          2
4   7 61  38 20 43       2             2             1          0
5  24 70  62 28 45       1             2             2          0
6  76 37  33 76 83       0             2             0          3