一列中因子变量的折叠级别,而另一列中的计数求和

时间:2018-11-04 12:53:20

标签: r forcats

我最初有各种各样的宽数据(4行158列),我使用reshape::melt()创建了一个长数据集(624行x 3列)。

但是,现在我有一个这样的数据集:

   demo <- data.frame(region = as.factor(c("North", "South", "East", "West")),
                       criteria = as.factor(c("Writing_1_a", "Writing_2_a", "Writing_3_a", "Writing_4_a", 
                                              "Writing_1_b", "Writing_2_b", "Writing_3_b", "Writing_4_b")), 
                       counts = as.integer(c(18, 27, 99, 42, 36, 144, 99, 9)))

哪个会生成与以下表格相似的表格:

     region   criteria      counts
     North    Writing_1_a       18
     South    Writing_2_a       27
     East     Writing_3_a       99
     West     Writing_4_a       42
     North    Writing_1_b       36
     South    Writing_2_b      144
     East     Writing_3_b       99
     West     Writing_4_b        9

现在我要创建的内容是这样的:

goal <- data.frame(region = as.factor(c("North", "South", "East", "West")),
                   criteria = as.factor(c("Writing_1", "Writing_2", "Writing_3", "Writing_4")), 
                   counts = as.integer(c(54, 171, 198, 51)))

表示当我合拢条件列时,它会对计数求和:

region  criteria     counts
North   Writing_1        54
South   Writing_2       171
East    Writing_3       198
West    Writing_4        51

我尝试使用forcats::fct_collapseforcats::recode(),但无济于事-我很肯定我做得不好。预先感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:0)

使用正则表达式的dplyr解决方案:

demo %>% 
  mutate(criteria = gsub("(_a)|(_b)", "", criteria)) %>%
  group_by(region, criteria) %>% 
  summarize(counts = sum(counts)) %>% 
  arrange(criteria) %>% 
  as.data.frame

  region  criteria counts
1  North Writing_1     54
2  South Writing_2    171
3   East Writing_3    198
4   West Writing_4     51

答案 1 :(得分:0)

您可以考虑要尝试执行哪些操作来更改因子级别-fct_collapse将多个级别手动折叠为一个级别,而fct_recode将手动更改各个级别的标签。您尝试做的是基于应用某些功能来更改所有标签,在这种情况下,fct_relabel是合适的。

您可以在调用fct_relabel时写出一个匿名函数,或仅将其名称传递给函数名称以及该函数的参数。在这种情况下,您可以使用stringr::str_remove查找和删除正则表达式模式,并使用_[a-z]$之类的正则表达式删除出现在字符串末尾的任何下划线和小写字母。这样,它就可以很好地与您的真实数据进行缩放,但是如果没有,您可以进行调整。

library(tidyverse)
...
new_crits <- demo %>%
  mutate(crit_no_digits = fct_relabel(criteria, str_remove, "_[a-z]$"))

new_crits
#>   region    criteria counts crit_no_digits
#> 1  North Writing_1_a     18      Writing_1
#> 2  South Writing_2_a     27      Writing_2
#> 3   East Writing_3_a     99      Writing_3
#> 4   West Writing_4_a     42      Writing_4
#> 5  North Writing_1_b     36      Writing_1
#> 6  South Writing_2_b    144      Writing_2
#> 7   East Writing_3_b     99      Writing_3
#> 8   West Writing_4_b      9      Writing_4

验证此新变量仅具有所需级别:

levels(new_crits$crit_no_digits)
#> [1] "Writing_1" "Writing_2" "Writing_3" "Writing_4"

然后根据该新因素进行总结:

new_crits %>%
  group_by(crit_no_digits) %>%
  summarise(counts = sum(counts))
#> # A tibble: 4 x 2
#>   crit_no_digits counts
#>   <fct>           <int>
#> 1 Writing_1          54
#> 2 Writing_2         171
#> 3 Writing_3         198
#> 4 Writing_4          51

reprex package(v0.2.1)于2018-11-04创建