我有一个数据框20,000个观察值和171个变量。每行中的每个值都是+1,0或-1。
我希望能够对每行中1的数量求和(或计数),并使该数字变量为172。
我研究了这个,但找不到解决方案。
rowsum()不合适,因为我不能像rowum那样使它有条件(df,= 1)
申请的情况也是如此。例如,以下代码不起作用:
apply(df, 1, sum(=1) ).
有没有办法计算行的条件和,其中只有符合条件的行中的那些值相加。
答案 0 :(得分:1)
如果您能提供人们可以使用的数据,那么它总是最好的。例如:
col1 col2 col3 col4
1 1 1 0 0
2 -1 0 -1 -1
3 0 -1 1 0
4 -1 -1 0 -1
5 -1 1 1 1
6 0 0 0 1
7 -1 -1 -1 1
8 1 -1 1 -1
9 0 -1 -1 1
10 0 1 1 -1
在我的案例中给了我们:
(df <- df %>% mutate(sums = rowSums(df == 1)))
col1 col2 col3 col4 sums
1 1 1 0 0 2
2 -1 0 -1 -1 0
3 0 -1 1 0 1
4 -1 -1 0 -1 0
5 -1 1 1 1 3
6 0 0 0 1 1
7 -1 -1 -1 1 1
8 1 -1 1 -1 2
9 0 -1 -1 1 1
10 0 1 1 -1 2
现在,您可以轻松实现您正在寻找的内容:
Application error
An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.