根据 R 中的唯一值合并/组合行

Merge/combine Row based on unique value in R

提问人:ahmad ilman ashraf bin fauzi 提问时间:2/17/2022 最后编辑:Maëlahmad ilman ashraf bin fauzi 更新时间:2/17/2022 访问量:39

问:

我的数据 :

enter image description here

我想要这样的输出:

enter image description here

我已经玩过 和 函数,但输出没有按照我想要的方式出现。aggregatemergegroup_by

R DataFrame 图论 操作 数据 清洗

评论

1赞 Nad Pat 2/17/2022
用于提供数据。dput(x)
0赞 vaettchen 2/17/2022
您可能还想更详细地解释如何从一个 DataFrame 转到另一个 DataFrame,而不是让我们猜测。

答:

0赞 Maël 2/17/2022 #1

一种方式,使用:tidyr::separate

d %>% 
  group_by(V1) %>% 
  summarise(V2 = toString(V2)) %>% 
  separate(V2, into = c("V2", "V1"))

# A tibble: 2 x 2
  V2    V1   
  <chr> <chr>
1 A     C    
2 B     D   
0赞 deschen 2/17/2022 #2

您可以执行以下操作:

library(tidyverse)

df <- data.frame(V1 = c(1,2,1,2),
                 V2 = LETTERS[1:4])

df %>%
  mutate(id = rep(1:2, each = 2)) %>%
  pivot_wider(names_from = V1,
              names_prefix = 'V',
              values_from = V2) %>%
  select(-id)

这给了:

# A tibble: 2 x 2
  V1    V2   
  <chr> <chr>
1 A     B    
2 C     D 
0赞 Tech Commodities 2/17/2022 #3

怎么样 -

library(dplyr)

df <- tibble(V1 = rep(1:2, 2), V2 = LETTERS[1:4])

df %>% 
  left_join(df, by = "V1") %>% 
  filter(V2.x != V2.y & V2.x %in% c("A", "B")) %>% 
  select(V1 = V2.y, V2 = V2.x)

# A tibble: 2 x 2
  V1    V2   
  <chr> <chr>
1 C     A    
2 D     B