gpt4 book ai didi

r - 使用索引将多行变为单行

转载 作者:行者123 更新时间:2023-12-04 08:50:38 26 4
gpt4 key购买 nike

根据这个输入:

structure(list(mid = c("text11", "text12", "text21", "text22", 
"text23"), term = c("test", "text", "section", "2", "sending"
)), class = "data.frame", row.names = c(NA, -5L))
怎么可能用mid来改造,把熔体排成单排。其中 text1, text2... text12 部分的中间显示行数和该行中存在的术语的新编号。用空格分隔合并它们。
数据框示例
data.frame(mid = c("text1", "text2"), term = c("test "text", "section 2 sending"
))

最佳答案

这应该工作

library(dplyr)
library(stringr)
df <- structure(list(mid = c("text11", "text12", "text21", "text22",
"text23"), term = c("test", "text", "section", "2", "sending"
)), class = "data.frame", row.names = c(NA, -5L))

df %>%
mutate(mid = str_extract(mid, "text\\d")) %>%
group_by(mid) %>%
summarise(term = paste(term, collapse=" "))
# # A tibble: 2 x 2
# mid term
# <chr> <chr>
# 1 text1 test text
# 2 text2 section 2 sending

编辑 - 解决评论
针对评论中的问题,下面的函数适用于除最后一位以外的所有数字都标识组的任何情况(即下面示例中的 1 和 12)。
df <- structure(list(mid = c("text11", "text12", "text121", "text122",  "text123"), term = c("test", "text", "section", "2", "sending")), class = "data.frame", row.names = c(NA, -5L))

df %>%
mutate(mid = str_sub(mid, 1, (nchar(mid)-1))) %>%
group_by(mid) %>%
summarise(term = paste(term, collapse=" "))

# # A tibble: 2 x 2
# mid term
# <chr> <chr>
# 1 text1 test text
# 2 text12 section 2 sending


关于r - 使用索引将多行变为单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64118770/

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