簡體   English   中英

如何在r的一行數據框中找到正負計數

[英]How to find count of positive and negative values in a row of dataframe in r

我在R中有一個數據框

      Loss1.       Loss2.         Loss3
     -456.             -2345.         -1290
       345.           -342.            234

我想計算正值和負值連續出現多少次。 預期輸出如下

      Loss1.      Loss2.      Loss3.   Neg_count.  Pos_count
      -456.       -2345.      -1290.        3.                  0
       345.         -342.          234.         1                  2

我嘗試使用rowsums,但是它給了我行的總數。 我如何在R中做到這一點?

下面的代碼應該工作:

dat <- data.frame(Loss1=c(-456,345),Loss2=c(-2345,-342),Loss3=c(-1290,234))
dat$Neg_Count <- rowSums(dat[,c("Loss1","Loss2","Loss3")]<0)
dat$Pos_Count <- rowSums(dat[,c("Loss1","Loss2","Loss3")]>0)
dat
 Loss1 Loss2 Loss3 Neg_Count Pos_Count
1  -456 -2345 -1290         3         0
2   345  -342   234         1         2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM