r - 使用 purrr 和 dplyr 将函数应用于列的子集

标签 r dplyr purrr

我是 purrr 包的新手,但我喜欢我对它的了解。

仅使用 tidyverse 包,我希望能够添加一个列,该列是应用于数据集中的列子集的函数的结果。

这是一些玩具数据。一系列因素列

df <- data.frame(a_1 = factor(rep(letters[1:3], times = 5)),
                 a_2 = factor(rep(letters[1:3], times = 5)),
                 a_3 = factor(rep(letters[1:3], times = 5)),
                 b_1 = factor(rep(letters[1:3], times = 5)),
                 b_2 = factor(rep(letters[1:3], times = 5)),
                 b_3 = factor(rep(letters[1:3], times = 5)))

df

# output
#  a_1 a_2 a_3 b_1 b_2 b_3
# 1    a   a   a   a   a   a
# 2    b   b   b   b   b   b
# 3    c   c   c   c   c   c
# 4    a   a   a   a   a   a
# 5    b   b   b   b   b   b
# 6    c   c   c   c   c   c
# 7    a   a   a   a   a   a
# 8    b   b   b   b   b   b
# 9    c   c   c   c   c   c
# 10   a   a   a   a   a   a
# 11   b   b   b   b   b   b
# 12   c   c   c   c   c   c
# 13   a   a   a   a   a   a
# 14   b   b   b   b   b   b
# 15   c   c   c   c   c   c

以下函数通过 purr::map_dfdplyr::select 循环遍历以 a_ 开头的 df 列,将将它们归为数字类,找到这些列的平均值,然后乘以 3。

rowMeans(purrr::map_df(.x = df %>% dplyr::select(grep("a_", names(.))),
                       .f = function(x) x <- as.numeric(x))*3)

# output
# [1] 3 6 9 3 6 9 3 6 9 3 6 9 3 6 9

这是正确的输出,但它是一个向量。

使用 tidyverse 函数,如何将函数的结果添加到现有 df 数据集作为新列而不是向量?

我猜想涉及到dplyr::mutate,但我无法解决。

最佳答案

您可以使用pmap_dbl:

library(dplyr)
library(purrr)

df %>%  
   mutate(mean_vec = pmap_dbl(select(., starts_with('a_')), 
                         ~mean(as.numeric(c(...)) * 3)))


#   a_1 a_2 a_3 b_1 b_2 b_3 mean_vec
#1    1   1   1   a   a   a        3
#2    2   2   2   b   b   b        6
#3    3   3   3   c   c   c        9
#4    1   1   1   a   a   a        3
#5    2   2   2   b   b   b        6
#6    3   3   3   c   c   c        9
#7    1   1   1   a   a   a        3
#8    2   2   2   b   b   b        6
#9    3   3   3   c   c   c        9
#10   1   1   1   a   a   a        3
#11   2   2   2   b   b   b        6
#12   3   3   3   c   c   c        9
#13   1   1   1   a   a   a        3
#14   2   2   2   b   b   b        6
#15   3   3   3   c   c   c        9

或者另一种选择:

df %>%
  mutate_at(vars(starts_with('a')), as.numeric) %>%
  mutate(mean_vec = rowMeans(select(., starts_with('a_')) * 3))

关于r - 使用 purrr 和 dplyr 将函数应用于列的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60842756/

相关文章:

r - 查找向量行中的部分文本 +[r]

r - 为什么 `mutate(across(...))` 和 `scale()` 将 [,1] 添加到列标题?

r - 给出由 purrr::map 名称返回的列表

r - 如何将字符串向量(每个给出命令)转换为 R 中的函数?

r - 如何从自定义存储库强制安装 R 包?

r - dplyr::summarise() 函数中的自动舍入

r - 如何在另一个数据框中使用变量+值查找替换单元格值?

r - 关于使用 rvest 和 purrr 抓取带有嵌套链接的多个页面的问题

r - 在 purrr 中提供 tibble 名称

r - 如何在Mac中使用Exiftool添加GPS纬度和经度(如何在jpeg中编辑元数据)