【问题标题】:Filter function throws error in data frame过滤器函数在数据框中抛出错误
【发布时间】:2020-10-08 16:34:23
【问题描述】:

我有一个包含因子的数据框。对于因子水平之一(etoh2),我想计算“从不”一词的出现次数,然后将其除以总数(不包括 na)来计算。百分比。

df 的结构如下所示: structure of df

并且 etoh2 的级别看起来像这样(使用 sapply):etoh levels

现在,我尝试使用 dplyr 进行过滤:

vipcls$etoh2 %>%
never <- count(filter(etoh2 == "never")
all <- count(etoh2)
ratio <- never/all

这给了我以下错误消息:error message

非常感谢任何帮助!

【问题讨论】:

    标签: r filter dplyr


    【解决方案1】:

    让我们解决这个问题。

    您的赋值运算符在错误的开始位置。管道 %>% 获取一个操作的输出并将其作为下一个操作的第一个参数。你正在尝试做

    vipcls$etoh2 %>%
      never # This is not a function
    

    这是正确的dplyr 方式。

    vipcls %>%
      filter(etoh2 == "never") %>% # makes your filtered set
      count() # returns the number of records
    

    要分配这个,你把你的分配放在前面:

    never <- vipcls %>%
      filter(etoh2 == "never") %>% # makes your filtered set
      count() # returns the number of records
    

    你可以更简单的获取all:

    all <- nrow(vipcls) #or
    all <- count(vipcls)
    

    您的代码count(etoh2) 将不起作用,因为etoh2 不是它自己的对象。它是vicpls 对象的一部分。

    【讨论】:

      【解决方案2】:

      你可以试试这个,Ben 已经解释得更好了。

      library(dplyr)
      
      etoh1 <- c("Hello,", "how", "are", "you", "today", "!", "Hello,", "how", "are", "you", "today", "!")`enter code here`
      etoh2 <- c("every day", "3-5/week", "1/week", "</1week", "<1/month", "never", "every day", "3-5/week", "1/week", "</1week", "<1/month", "never")
      
      vipcls <- data.frame(cbind(etoh1, etoh2))
      never <- count(vipcls %>% 
                       filter(etoh2 == "never"))
      all <- nrow(vipcls) #assuming total rows = total etoh2
      ratio <- never/all
      
      ratio
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-25
        • 1970-01-01
        • 2015-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多