映射到特定的组,在R中使用purrr
purrr新问题: 我试图通过使用map()包在R中的组之间应用一个函数来对代码进行矢量化,但我似乎做得不对。下面是我的示例,跨越复制粘贴、for循环,然后映射示例映射到特定的组,在R中使用purrr,r,vectorization,purrr,R,Vectorization,Purrr,purrr新问题: 我试图通过使用map()包在R中的组之间应用一个函数来对代码进行矢量化,但我似乎做得不对。下面是我的示例,跨越复制粘贴、for循环,然后映射示例 species <- rep(seq(1:3), times = 10) bio_data <- bind_cols(length = rnorm(n = 30, mean = 50, sd = 25), weight = rnorm(n = 30, mean = 100,
species <- rep(seq(1:3), times = 10)
bio_data <- bind_cols(length = rnorm(n = 30, mean = 50, sd = 25),
weight = rnorm(n = 30, mean = 100, sd = 35))
dat <- bind_cols(species = species, bio_data)
# test --------------------------------------------------------------------
# manually get mean by species:
dat %>% filter(species == 1) %>% summarize(mean_wt = mean(weight))
dat %>% filter(species == 2) %>% summarize(mean_wt = mean(weight))
dat %>% filter(species == 3) %>% summarize(mean_wt = mean(weight))
# create function and loop over function:
get_mean <- function(data, group){
data %>%
dplyr::filter(species == group) %>%
summarise(mean_wt = mean(weight))
}
for(i in unique(species)){
print(get_mean(dat, i))
}
# use purrr map() package
results <- map(dat, get_mean, group = unique(species))
如何让我的代码生成每个物种的平均权重?循环应为
唯一(物种)
-输出
#[[1]]
# A tibble: 1 x 1
# mean_wt
# <dbl>
#1 88.2
#[[2]]
# A tibble: 1 x 1
# mean_wt
# <dbl>
#1 105.
#[[3]]
# A tibble: 1 x 1
# mean_wt
# <dbl>
#1 124.
# A tibble: 3 x 2
# species mean_wt
#* <int> <dbl>
#1 1 88.2
#2 2 105.
#3 3 124.
-输出
#[[1]]
# A tibble: 1 x 1
# mean_wt
# <dbl>
#1 88.2
#[[2]]
# A tibble: 1 x 1
# mean_wt
# <dbl>
#1 105.
#[[3]]
# A tibble: 1 x 1
# mean_wt
# <dbl>
#1 124.
# A tibble: 3 x 2
# species mean_wt
#* <int> <dbl>
#1 1 88.2
#2 2 105.
#3 3 124.
#一个tible:3 x 2
#物种平均值
#*
#1 1 88.2
#2 2 105.
#3 3 124.
Aha!如此接近,却又如此遥远。谢谢你的帮助!
# A tibble: 3 x 2
# species mean_wt
#* <int> <dbl>
#1 1 88.2
#2 2 105.
#3 3 124.