gpt4 book ai didi

r - 我如何使用 pivot wider 按组进行汇总

转载 作者:行者123 更新时间:2023-12-04 16:37:42 24 4
gpt4 key购买 nike

df <- data.frame( plant1= c('1','0','1','0','0','1','0','0','1'),
plant2= c('0','1','0','1','1','0','1','1','0'),
Public.1= c('1','0','1','0','0','0','0','0','1'),
Private.1= c('0','0','0','0','0','1','0','0','0'),
Public.2= c('0','0','0','1','1','0','0','1','0'),
Private.2= c('0','1','0','0','0','0','1','0','0'))
df

我如何根据 Plant1 和 2 使用 pivot wider 来总结 Public Private?逻辑背后:每个 Plant 元素只能注册 Public 或 Privateplant 1和Public.1 Private.1相关

预期输出:

 plant1 plant2 Public Private 
1 1 0 1 0
2 0 1 0 1
3 1 0 1 0
4 0 1 1 0
5 0 1 1 0
6 1 0 0 1
7 0 1 0 1
8 0 1 1 0
9 1 0 1 0

最佳答案

我们可以使用names_sep

library(tidyr)
library(dplyr)
pivot_longer(df,
cols = matches('Public|Private'),
names_to = c(".value", 'grp'), names_sep ="\\.") %>%
select(-grp)

-输出

# A tibble: 18 x 4
plant1 plant2 Public Private
<chr> <chr> <chr> <chr>
1 1 0 1 0
2 1 0 0 0
3 0 1 0 0
4 0 1 0 1
5 1 0 1 0
6 1 0 0 0
7 0 1 0 0
8 0 1 1 0
9 0 1 0 0
10 0 1 1 0
11 1 0 0 1
12 1 0 0 0
13 0 1 0 0
14 0 1 0 1
15 0 1 0 0
16 0 1 1 0
17 1 0 1 0
18 1 0 0 0

关于r - 我如何使用 pivot wider 按组进行汇总,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67400039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com