r - Concatenate Column Strings based on an Integer -
i want create strings shown below date first elected, example.
df:
name party firstelected bob liberal 1985 joe republican 1985 sarah green 1980 bill libertarian 1980 tom conservative 1987
goal:
year peopleelected 1985 "bob (liberal); joe (republican)" 1980 "sarah (green); bill (libertarian)" 1987 "tom (conservative)"
i assume combination of paste
, apply/aggregate
can this...but haven't had luck far.
we can use paste/sprintf
create format grouped 'firstelected'. convert 'data.frame' 'data.table' (setdt(df1)
), grouped 'firstelected', wrap 'party' parentheses, concatenate 'name' using sprintf
, use paste
, collapse='; '
create single string.
library(data.table) setdt(df1)[,list(peopleelected=paste(sprintf('%s (%s)', name, party), collapse="; ")) , = firstelected] # firstelected peopleelected #1: 1985 bob (liberal); joe (republican) #2: 1980 sarah (green); bill (libertarian) #3: 1987 tom (conservative)
or using single paste
setdt(df1)[, list(peopleelected=paste(name, ' (', party, ')', sep='', collapse='; ')) , by=firstelected]
Comments
Post a Comment