【问题标题】:Count freq values and keep all rows - multiple conditions计算频率值并保留所有行 - 多个条件
【发布时间】:2018-01-05 03:41:33
【问题描述】:

考虑到整个数据集,我需要创建一个频率为两个条件(在每一行中定义)的新列。

请注意,我需要添加此信息并保留之前数据集中的所有行。

例子:

library(datasets)
mydata<-CO2
names(mydata)
[1] "Plant"     "Type"      "Treatment" "conc"      "uptake"  

假设我想使用变量“类型”和“治疗”作为我的条件。 因此,我需要为每一行计算相应的“类型”和“治疗”在整个数据集中出现的次数。

【问题讨论】:

  • 您需要为每一行计算“类型”和“治疗”各自的组合出现了多少次?
  • 正是这个!谢谢。

标签: r count frequency


【解决方案1】:

您可以使用ave 来计算每个分组对的长度:

mydata$freq <- ave(rep(1, nrow(mydata)), mydata$Type, mydata$Treatment, FUN = length)

head(mydata)
#  Plant   Type  Treatment conc uptake freq
#1   Qn1 Quebec nonchilled   95   16.0   21
#2   Qn1 Quebec nonchilled  175   30.4   21
#3   Qn1 Quebec nonchilled  250   34.8   21
#4   Qn1 Quebec nonchilled  350   37.2   21
#5   Qn1 Quebec nonchilled  500   35.3   21
#6   Qn1 Quebec nonchilled  675   39.2   21

【讨论】:

  • 跟我做的一模一样,你比我快几十秒。
  • 啊,我只是想到了它,因为我刚刚用非常相似的解决方案回答了另一个问题!
【解决方案2】:

您可以使用dplyr 包轻松做到这一点

library(dplyr)
mydata %>% group_by(Type,Treatment) %>% summarize(count = n())

会导致

# A tibble: 4 x 3
# Groups:   Type [?]
         Type  Treatment count
       <fctr>     <fctr> <int>
1      Quebec nonchilled    21
2      Quebec    chilled    21
3 Mississippi nonchilled    21
4 Mississippi    chilled    21

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 2020-09-08
    • 2018-11-24
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多