gpt4 book ai didi

r - 基于整数连接列字符串

转载 作者:行者123 更新时间:2023-12-01 08:33:04 24 4
gpt4 key购买 nike

例如,我想按首次选举的日期创建如下所示的字符串。

df:

Name         Party       FirstElected
Bob Liberal 1985
Joe Republican 1985
Sarah Green 1980
Bill Libertarian 1980
Tom Conservative 1987

目标:

Year            PeopleElected
1985 "Bob (Liberal); Joe (Republican)"
1980 "Sarah (Green); Bill (Libertarian)"
1987 "Tom (Conservative)"

我假设pasteapply/aggregate的某种组合可以做到这一点......但到目前为止我还没有太多运气。

最佳答案

我们可以使用paste/sprintf创建按“FirstElected”分组的格式。我们将“data.frame”转换为“data.table”( setDT(df1) ),按“FirstElected”分组,用括号将“Party”括起来,使用 sprintf 连接“Name” ,然后使用paste ,与 collapse='; '创建单个字符串。

library(data.table)
setDT(df1)[,list(PeopleElected=paste(sprintf('%s (%s)',
Name, Party), collapse="; ")) , by = FirstElected]
# FirstElected PeopleElected
#1: 1985 Bob (Liberal); Joe (Republican)
#2: 1980 Sarah (Green); Bill (Libertarian)
#3: 1987 Tom (Conservative)

或者使用单个paste

setDT(df1)[, list(PeopleElected=paste(Name, ' (', Party, ')',
sep='', collapse='; ')) , by=FirstElected]

关于r - 基于整数连接列字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32692617/

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