group_by
我不想为每个df
的每个唯一集合编写新的代码块,而是创建一个循环遍历List_Of_Groups <- map_df(df, function(i) {
df %>%
group_by(!!!syms(names(df)[1:i])) %>%
summarize(newValue = mean(A))
})
数据框并将结果保存到列表或数据中的循环帧。
我想看看特征 A 的平均值如何随特征 B 和 C 扩展,而不必编写新的数据集中每个分类特征的代码块。
我尝试过:
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
fit: StackFit.expand,
children: [
Image.network(
'https://lh3.googleusercontent.com/proxy/_wrP_GRGOkGw0FLMiR3qeMzlyC-qN8Dd4sND89_xxLZMDIZh204g8PCccS-o9WaL1RKyiVOLGVS9QpodSkMMhOh8kbNh1CY492197-im-4vlFRRdsVqT2g4QbRlNgljDIg',
fit: BoxFit.cover,
), //Give your Image here
ColorFiltered(
colorFilter: ColorFilter.mode(
Colors.black.withOpacity(0.5),
BlendMode.srcOut,
), // This one will create the magic
child: Stack(
fit: StackFit.expand,
children: [
Container(
decoration: BoxDecoration(
color: Colors.black,
backgroundBlendMode: BlendMode.dstOut,
), // This one will handle background + difference out
),
Align(
alignment: Alignment.center,
child: Container(
height: MediaQuery.of(context).size.width,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(
MediaQuery.of(context).size.width / 2,
),
),
),
),
],
),
),
],
),
);
}
答案 0 :(得分:5)
使用purrr
的{{1}},可以将指定的代码块应用于字符的所有列。基本上,您将字符变量的名称映射到
map
输出
purrr::map(names(df %>% select(where(is.character))), function(i) {
df %>%
group_by(!!sym(i)) %>%
summarize(newValue = mean(A))
})
答案 1 :(得分:2)
您可以使用A作为标识符将其旋转很长时间,然后分组依据:
library(tidyr)
df %>% pivot_longer(-A) %>% group_by(name,value) %>% summarize(val=mean(A))
# A tibble: 6 x 3
# Groups: name [2]
name value val
<chr> <fct> <dbl>
1 B Group 1 7
2 B Group 2 3.5
3 B Group 3 4
4 C Group 1 5
5 C Group 2 8.5
6 C Group 3 1.5
答案 2 :(得分:1)
您可以尝试这样的事情:
library(dplyr)
empty_list <- list(0)
for(i in 2:dim(df)[2])
{
empty_list[[i-1]]<-df %>% group_by(df[,i]) %>% summarise(val = mean(A))
}
empty_list
[[1]]
# A tibble: 3 x 2
`df[, i]` val
<fct> <dbl>
1 Group 1 7
2 Group 2 3.5
3 Group 3 4
[[2]]
# A tibble: 3 x 2
`df[, i]` val
<fct> <dbl>
1 Group 1 5
2 Group 2 8.5
3 Group 3 1.5
希望这会有所帮助。