将多个列变为函数会为dplyr中的结果列内的每个组件创建一个列表

问题描述 投票:2回答:2

我有一个函数从一个包(tidycensus),我想通过管道和变异使用它。我创建了这个简单的模型来展示这种情况。

library(tidycensus)

tt <- as_data_frame(matrix(1:36, ncol = 6))
colnames(tt) <- c("A", "B", "C", "D", "E", "F")
tt2 <- tt %>% mutate(moe=moe_prop(.[,"A"],.[,"C"], .[,"D"],.[,"B"]))

最终结果将结果包装到列表中(所有结果都与每个列表中的计算值相等)并将它们放在moe列的每个位置,如下所示。显然,我想要一个矢量作为填充列moe的结果

> tt2
# A tibble: 6 x 7
      A     B     C     D     E     F    moe      
    <int> <int> <int> <int> <int> <int> <list>   
1     1     7    13    19    25    31 <dbl [6]>
2     2     8    14    20    26    32 <dbl [6]>
3     3     9    15    21    27    33 <dbl [6]>
4     4    10    16    22    28    34 <dbl [6]>
5     5    11    17    23    29    35 <dbl [6]>
6     6    12    18    24    30    36 <dbl [6]>

我知道使用[,"Column_name]格式返回列表。因此,我尝试将每个输入变量的as.vector添加到函数中。还是一样的结果。我想知道我在这里失踪了什么。

r dplyr tidyverse tidycensus
2个回答
1
投票

基于输入数据集,假设我们每行只需要一个值,通过在每一行上执行moe_prop,将列名转换为符号然后进行评估(!!!

tt %>% 
  mutate(moe = moe_prop(!!! rlang::syms(names(.)[c(1, 3, 4, 2)])))
# A tibble: 6 x 7
#      A     B     C     D     E     F   moe
#  <int> <int> <int> <int> <int> <int> <dbl>
#1     1     7    13    19    25    31  1.46
#2     2     8    14    20    26    32  1.43
#3     3     9    15    21    27    33  1.39
#4     4    10    16    22    28    34  1.37
#5     5    11    17    23    29    35  1.34
#6     6    12    18    24    30    36  1.31

它类似于通话

tt %>%
   mutate(moe = moe_prop(!!! rlang::syms(c("A", "C", "D", "B"))))

或者执行rowwise()操作

tt %>%
    rowwise %>% 
    mutate(moe = moe_prop(A, C, D, B))

通过单独检查行值

moe_prop(1, 13, 19, 7)
#[1] 1.460951

moe_prop(2, 14, 20, 8)
#[1] 1.426237

1
投票

你可以使用unnest()

library(dplyr)
library(tidyr)
library(tidycensus)

tt <- as_data_frame(matrix(1:36, ncol = 6))
colnames(tt) <- c("A", "B", "C", "D", "E", "F")
tt2 <- tt %>% 
  mutate(moe = moe_prop(.[, "A"], .[, "C"], .[, "D"], .[, "B"]))

tt2 %>%
  unnest()
#> # A tibble: 36 x 7
#>        A     B     C     D     E     F   moe
#>    <int> <int> <int> <int> <int> <int> <dbl>
#>  1     1     7    13    19    25    31  1.46
#>  2     1     7    13    19    25    31  1.43
#>  3     1     7    13    19    25    31  1.39
#>  4     1     7    13    19    25    31  1.37
#>  5     1     7    13    19    25    31  1.34
#>  6     1     7    13    19    25    31  1.31
#>  7     2     8    14    20    26    32  1.46
#>  8     2     8    14    20    26    32  1.43
#>  9     2     8    14    20    26    32  1.39
#> 10     2     8    14    20    26    32  1.37
#> # ... with 26 more rows

reprex package创建于2018-09-12(v0.2.0.9000)。

© www.soinside.com 2019 - 2024. All rights reserved.