2014-09-01 71 views
1

我希望獲取數據幀的每一行的條目數> 0,例如獲取具有此行數的新列。根據條件在數據框中進行行計數

我執行了一個循環,我可以獲得行數,但它們被打印爲一系列單獨的向量。如何在單列中獲取這些值,然後可以將其添加爲我的df中的列?

我有一個df 696行和214列。

for (i in 2:696) { 
    casecount <- length(which(testset[i,13:214] > 0)) 
    print(casecount) 
}  

回答

1

無需在for循環,只是做

testset$casecount <- rowSums(testset[, 13:214] > 0) 
0

嘗試使用rowSums這樣的:

n <- 10 

set.seed(0) 
dat <- data.frame(x=rnorm(n), y=rnorm(n), z=rnorm(n)) 
dat$count <- rowSums(dat > 0) 
dat 

       x   y   z count 
1 1.262954285 0.7635935 -0.22426789  2 
2 -0.326233361 -0.7990092 0.37739565  1 
3 1.329799263 -1.1476570 0.13333636  2 
4 1.272429321 -0.2894616 0.80418951  2 
5 0.414641434 -0.2992151 -0.05710677  1 
6 -1.539950042 -0.4115108 0.50360797  1 
7 -0.928567035 0.2522234 1.08576936  2 
8 -0.294720447 -0.8919211 -0.69095384  0 
9 -0.005767173 0.4356833 -1.28459935  1 
10 2.404653389 -1.2375384 0.04672617  2 
相關問題