【问题标题】:Iterate through columns and row values (list) in R dplyr遍历 R dplyr 中的列和行值(列表)
【发布时间】:2018-11-07 08:35:21
【问题描述】:

此问题基于以下帖子,有额外要求 (Iterate through columns in dplyr?)。

原代码如下:

df <- data.frame(col1 = rep(1, 15),
      col2 = rep(2, 15),
      col3 = rep(3, 15),
      group = c(rep("A", 5), rep("B", 5), rep("C", 5)))

for(col in c("col1", "col2", "col3")){
      filt.df <- df %>%
      filter(group == "A") %>% 
      select_(.dots = c('group', col))
      # do other things, like ggplotting
      print(filt.df)
}

我的目标是按 GROUP 组合为每个唯一的 COL 输出频率表。当前示例基于 GROUP 值 A、B 或 C 指定 dplyr 过滤器。在我的情况下,我想遍历(循环)GROUP 中的值列表(list

频率表基于计数。对于 Col1,结果类似于下表。示例数据集已简化。我的真实数据集更复杂,每个“组”有多个“值”。我需要按组遍历 Col1-Col3。

组值 n 属性
A      1      5    .1
B      2      5     .1
C     3      5    .1

频率表的一个更好的例子在这里:How to use dplyr to generate a frequency table

我为此苦苦挣扎了几天,我本可以用我的例子做得更好。感谢您的帖子。这就是我最终为解决这个问题所做的事情。结果是每列和组中找到的每个唯一值的一系列频率表。我有 3 列(col1、col2、col3)和组(A、B、C)中的 3 个唯一值,3x3。结果是 9 个频率表和每个组值的频率表是无意义的。我确信有更好的方法来做到这一点。输出会生成一些标签,这很有用。

# Build unique group list
group <- unique(df$group)

# Generate frequency tables via a loop
iterate_by_group <- function(x)
 for (i in 1:length(group)){ 
  filt.df <- df[df$group==group[i],]
  print(lapply(filt.df, freq))
}

# Run 
iterate_by_group(df)

【问题讨论】:

    标签: r loops filter dplyr


    【解决方案1】:

    这是你想要的吗?

    df %>%
      group_by(group) %>%
      summarise_all(funs(freq = sum))
    

    【讨论】:

    • 频率表不太正确,我添加了一个示例链接。事实证明,我的数据示例不是很好。我最终使用了一个基于 group 唯一值的函数,然后使用 lapply 遍历每一列。发布在我最初的帖子中。
    【解决方案2】:

    我们可以将gather转换成长格式,然后按组得到频率(n()

    library(tidyverse)
    gather(df, value, val, col1:col3) %>%
            group_by(group, value = parse_number(value)) %>% 
            summarise(n = n(), prop = n/nrow(.))
    # A tibble: 9 x 4
    # Groups:   group [?]
    #  group value     n  prop
    #  <fct> <dbl> <int> <dbl>
    #1 A         1     5 0.111
    #2 A         2     5 0.111
    #3 A         3     5 0.111
    #4 B         1     5 0.111
    #5 B         2     5 0.111
    #6 B         3     5 0.111
    #7 C         1     5 0.111
    #8 C         2     5 0.111
    #9 C         3     5 0.111
    

    【讨论】:

    • 感谢您的 cmets。我更新了我原来的帖子。
    猜你喜欢
    • 1970-01-01
    • 2017-02-11
    • 2016-09-19
    • 2014-09-26
    • 1970-01-01
    • 2016-06-28
    • 2022-11-15
    • 2021-11-19
    • 1970-01-01
    相关资源
    最近更新 更多