简体   繁体   English

如何在r的一行数据框中找到正负计数

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

I have a dataframe in r 我在R中有一个数据框

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

I want to calculate how many times positive and negative value occurs in a row. 我想计算正值和负值连续出现多少次。 Expected output is as follows 预期输出如下

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

I tried with rowsums,but it gives me sum of rows. 我尝试使用rowsums,但是它给了我行的总数。 How can I do it in r? 我如何在R中做到这一点?

The code below should work: 下面的代码应该工作:

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.

相关问题 向 dataframe 添加新列,其中包含一行中正值的总和和一行中的负值总和 - R - Add new columns to a dataframe containing sum of positive values in a row and sum of negative values in a row - R 如何根据正负值在R中找到条件和 - How to find conditional sum in R based on positive and negative values R-查找正/负值的最大游程 - R - Find maximum run of positive / negative values 将行中的负/正值除以r中的另一行? - Divide negative/positive values in row by another row in r? 在数据框中添加一行以显示幅度(正值或负值之和的最大值) - Add a row to a dataframe showing amplitude (max of the sum of the positive or the negative values) 计数 R 中每列的负值、0 和正值的数量和百分比 - Count numbers and percentage of negative, 0 and positive values for each column in R 从R数据框中删除负值和一个正值 - Removing negative values and one positive value from R dataframe 将 R 数据帧输出到 .txt 文件 - 对齐正负值 - Outputting an R dataframe to a .txt file - Align positive and negative values 如何计算带有文本和日期值的.csv文件列表中特定正负词的出现频率? 在R中 - How to count frequency of specific positive/negative words from a list in a .csv file with text and date values? in R R 只找到正值或负值 tidyverse - R across find only positive or only negative values tidyverse
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM