【问题标题】:Is there a R function to count the values in the rows more than 0 [duplicate]是否有一个 R 函数来计算行中的值超过 0 [重复]
【发布时间】:2019-07-10 15:41:50
【问题描述】:

是否有R函数可以连续计算大于0的值

  test <- data.frame(a=c(a,"y"),b=c(0,"5"),c=c(2,"0"))
  test
  a b c
1 1 0 2
2 y 5 0

我需要关注,因为第一行包含 1 个大于 0 的值,第二行包含 1 个大于 0 的值。我需要排除第一列,因为它只是字符

test
  a b c d
1 a 0 2 1
2 y 5 0 1

【问题讨论】:

  • 如果你创建testtest &lt;- data.frame(a=c(1,0),b=c(0,1),c=c(2,0)),你可以做rowSums(test &gt; 0)
  • 谢谢。对不起,一个小改动,假设数据集中有一个字符。我需要排除它,然后计算。问题已编辑
  • c(0,"5") 给出一个字符向量,即与c("0","5") 相同 - 所以给我们一个可重现的例子minimal reproducible example
  • @JanP 试试这个type.convert(test, as.is = TRUE) %&gt;% select_if(is.numeric) %&gt;% is_greater_than(0) %&gt;% rowSums

标签: r


【解决方案1】:

我们可以将列的type 转换为type.convert,选择数字列,检查它是否大于0,得到逻辑矩阵的逐行和,并在“测试”数据集中创建一个新列

library(tidyverse)
library(magrittr)
type.convert(test, as.is = TRUE) %>%
    select_if(is.numeric) %>%
    is_greater_than(0) %>% 
    rowSums %>%
    bind_cols(test, d = .)
#  a b c d
#1 a 0 2 1
#2 y 5 0 1

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    相关资源
    最近更新 更多