R 将双列拆分为单独的列并合并相同的命名列
这是一个棘手的问题,我真的很高兴听到解决办法。 我有我称之为“双栏”的栏目,即内容可以分为两个独立栏目的栏目 这是我的意见:R 将双列拆分为单独的列并合并相同的命名列,r,multiple-columns,tidyverse,purrr,R,Multiple Columns,Tidyverse,Purrr,这是一个棘手的问题,我真的很高兴听到解决办法。 我有我称之为“双栏”的栏目,即内容可以分为两个独立栏目的栏目 这是我的意见: structure(list(`A1-A2` = c(2, 1, 1), `A1-A3` = c(2, 1, 2)), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame")) # A tibble: 3 x 2 `A1-A2` `A1-A3` <dbl> <d
structure(list(`A1-A2` = c(2, 1, 1), `A1-A3` = c(2, 1, 2)), row.names = c(NA,
-3L), class = c("tbl_df", "tbl", "data.frame"))
# A tibble: 3 x 2
`A1-A2` `A1-A3`
<dbl> <dbl>
1 2 2
2 1 1
3 1 2
两大挑战:
A1-A2、A1-A3、A2-A3
时,它们将出现两次A1、A2、A3
),如何避免出现问题tidyverse(purrr::map)
中的方法,但我对其他解决方案持开放态度
这很棘手,不是吗?我在@akrun的帮助下制定了这个解决方案,他启发我将
pivot\u更长的时间和在情况下变异。如果有人有一个更优雅或更短的解决方案,请张贴
data
# A tibble: 3 x 2
`A1-A2` `A1-A3`
<dbl> <dbl>
1 2 2
2 1 1
3 1 2
comparisons <- data %>%
pivot_longer(everything()) %>%
separate(name, c("V1", "V2"), sep = "-") %>%
mutate(win = case_when(value == 2 ~ V2, TRUE ~ V1)) %>%
select(-value) %T>% print
# A tibble: 6 x 3
V1 V2 win
<chr> <chr> <chr>
1 A1 A2 A2
2 A1 A3 A3
3 A1 A2 A1
4 A1 A3 A1
5 A1 A2 A1
6 A1 A3 A3
scores <- comparisons %>%
group_by(win) %>%
tally() %>%
pivot_wider(names_from = win, values_from = n) %T>% print
# A tibble: 1 x 3
A1 A2 A3
<int> <int> <int>
1 3 1 2
数据
#一个tibble:3x2
`A1-A2``A1-A3`
1 2 2
2 1 1
3 1 2
比较%
pivot_更长(所有内容())%>%
单独(名称,c(“V1”、“V2”),sep=“-”%>%
变异(win=case_,当(值==2~V2,真~V1))%>%
选择(-value)%T>%print
#一个tibble:6x3
胜利
1 A1 A2 A2
2 A1 A3 A3
3 A1 A2 A1
4 A1 A3 A1
5 A1 A2 A1
6 A1 A3 A3
分数%
组别(获胜)%>%
计数()%>%
透视图(名称从=win,值从=n)%T>%print
#一个tibble:1 x 3
A1 A2 A3
1 3 1 2
很抱歉,我本想给你更多的信任,但在解决方案中提到了你。可以我想你现在有办法了。全部的很好,再次感谢你的帮助,@akrun-你是最棒的!很高兴帮助你
# A tibble: 1 x 3
A1 A2 A3
1 3 1 2
data
# A tibble: 3 x 2
`A1-A2` `A1-A3`
<dbl> <dbl>
1 2 2
2 1 1
3 1 2
comparisons <- data %>%
pivot_longer(everything()) %>%
separate(name, c("V1", "V2"), sep = "-") %>%
mutate(win = case_when(value == 2 ~ V2, TRUE ~ V1)) %>%
select(-value) %T>% print
# A tibble: 6 x 3
V1 V2 win
<chr> <chr> <chr>
1 A1 A2 A2
2 A1 A3 A3
3 A1 A2 A1
4 A1 A3 A1
5 A1 A2 A1
6 A1 A3 A3
scores <- comparisons %>%
group_by(win) %>%
tally() %>%
pivot_wider(names_from = win, values_from = n) %T>% print
# A tibble: 1 x 3
A1 A2 A3
<int> <int> <int>
1 3 1 2