我有一个包的功能(tidy普查),我想通过管道和变异来使用它。我创造了这个简单的模型来展示情况。
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。结果还是一样。我想知道我在这里错过了什么。
发布于 2018-09-12 16:28:05
根据输入数据集,假设每一行只需要一个值,对每一行执行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"))))或执行行()操作
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发布于 2018-09-12 16:31:58
您可以使用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封装创建于2018-09-12 (v0.2.0.9000)。
https://stackoverflow.com/questions/52299681
复制相似问题