gpt4 book ai didi

r - 合并数据框中的行而不分组

转载 作者:行者123 更新时间:2023-12-04 09:16:13 26 4
gpt4 key购买 nike

tibble::tibble(
col1 = c("A","","C","",""),
col2 = c("string1 part 1","string1 part 2",
"string2 part 1", "string2 part 2",
"string3"),
col3 = c(1, "", 2, "", 3)
)

我想合并 col2 中的行, 像这样获得一个没有空字符串的 tibble

tibble::tibble(
col1 = c("A","C",NA),
col2 = c("string1 part 1 string1 part 2", "string2 part 1 string2 part 2", "string3"),
col3 = c(1,2,3)
)

# A tibble: 3 x 3
col1 col2 col3
<chr> <chr> <dbl>
1 A string1 part 1 string1 part 2 1
2 C string2 part 1 string2 part 2 2
3 NA string3 3

正如我在其他答案中发现的那样,分组似乎不是一个选项,而我没有任何引用列

最佳答案

这适用于 dplyr

tibble::tibble(
col1 = c("A","","C","",""),
col2 = c("string1 part 1","string1 part 2",
"string2 part 1", "string2 part 2",
"string3"),
col3 = c(1, "", 2, "", 3)
) %>%
# fill empty values on col3
mutate(col3 = case_when(
col3!="" ~ 1,
T ~ 0
)) %>%
mutate(col3 = cumsum(col3)) %>%
# fill empty values on col1
group_by(col3) %>%
mutate(col1 = first(col1)) %>%
# group & summarise
group_by(col1, col3) %>%
summarise(col2 = paste(col2, collapse=' ')) %>%
# replace empty string by NA & arrange by col3
ungroup() %>%
mutate(col1 = case_when(
col1=="" ~ as.character(NA),
T ~ col1
)) %>%
arrange(col3) %>%
select(col1, col2, col3)

输出 :
# A tibble: 3 x 3
# col1 col2 col3
# <chr> <chr> <dbl>
#1 A string1 part 1 string1 part 2 1
#2 C string2 part 1 string2 part 2 2
#3 <NA> string3 3

关于r - 合并数据框中的行而不分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59412291/

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