r - 如何将列表元素提取到 r 中的多个 tibble 列中?

标签 r list dplyr tibble

我有一个非常大的 tibble 形式的数据集。我想使用一些返回列表的函数来总结数据。我对列表的几个组件感兴趣,我想将我需要的每个组件返回到新的 tibble 列中。

举个例子

library(tibble)
library(dplyr)

# Create a data set of 1,000 random values in 100 subgroups with sample size 10
contrived_data <- tibble(subgroup = rep(1:100, each = 10),
                         value    = rnorm(1000, mean = 5, sd = 1))


# Run the KS test vs. normal distribution on each sample of size 10. Return the KS statistic and p-value
# into new tibble columns
contrived_data %>% group_by(subgroup) %>%
  summarize(avg     = mean(value),
            std_dev = sd(value),
            ks_stat = ks.test(value, "pnorm", mean = 5, sd = 1)$statistic,
            ks_pval = ks.test(value, "pnorm", mean = 5, sd = 1)$p.value)

以这种方式运行它可以得到我想要的结果,但效率不高。调用 ks.test 函数两次意味着执行时间(几乎)加倍。似乎必须有一种更有效的方法来通过单个函数调用提取这两个列表组件,但我不知道该怎么做。

最佳答案

您可以定义函数并使用来自 purrr 的 map :

library(tibble)
library(dplyr)
library(purrr)

func = function(DA){
kstest = ks.test(DA$value, "pnorm", mean = 5, sd = 1)
data.frame(
subgroup = unique(DA$subgroup),
avg=mean(DA$value),
std_dev = sd(DA$value),
ks_stat = kstest$statistic,
ks_pval = kstest$p.value)
}

contrived_data %>% 
split(.$subgroup) %>%
map_dfr(func)

关于r - 如何将列表元素提取到 r 中的多个 tibble 列中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59269319/

相关文章:

r - 检查 data.table 是否键入函数,R

RS Selenium : replacing xpath with variable in R

python - 在python中从一个列表中的另一个列表中查找元素

R Shiny : conditionalPanel not working if used in different tabs

r - geom_密度未使用scale_y_log10正确填充

html - 推特 Bootstrap : position list elements by first letter around the center (almost centered)

python - 为什么排序列表比未排序列表大

r - 在 R 中:将列名作为参数传递,并在 dplyr::mutate() 和 lazyeval::interp() 的函数中使用它

r - 如何识别两(或更多)行不同(相同 ID)的列?

r - 使用 dplyr 条件替换 tibble 中的列名