给定行的列值数量大于0? [英] Number of column values greater than 0 for given row?

查看:57
本文介绍了给定行的列值数量大于0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据框:

I have a dataframe which looks like:

col1  col2  col3
0     0     .4
.3    1     0
0     0     .8

我想创建一个新列,该列计算其他三行中大于0的列值的数量:

I'd like to create a new column which counts the number of column values greater than 0 in the other three rows:

col1  col2  col3  col4
0     0     .4    1
.3    1     0     2
0     0     .8    1

推荐答案

您只需要使用 apply 函数:

## Example Data
dd = data.frame(col1 = c(0, .3, 0), col2=c(0, 1, 0),
                        col3=c(0.4, 0, 0.8))
apply(dd, 1, function(i) sum(i > 0))

因此,也要将它添加到您现有的数据框中:

So to add this too your existing data frame:

dd$col4 =  apply(dd, 1, function(i) sum(i > 0))


或者,我们可以将数据帧转换为逻辑值,然后使用 rowSums

rowSums(dd > 0)

这篇关于给定行的列值数量大于0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆