Home > OS >  Inserting text inbetween text in a string in r
Inserting text inbetween text in a string in r

Time:11-11

I'm working with a data frame that looks think this:

character <- c("ab",  "acr", "sb",  "ab",  "ab",  "sjr" )
numbers <- c("2823", 
             "2093",  
             "651",                                                                                        
             "876 1604",                                                                                        
             "772 1604 1932",                                                          
             "241 1110 1342 1822" )

df <- data.frame(character, numbers)
df

I want to insert the character values in the character column before each number in the number column.

Such that the output looks like this:


output <- c(  "ab 2823", 
             "acr 2093",  
             "sb 651",                                                                                        
             "ab 876 ab 1604",                                                                                        
             "ab 772 ab 1604 ab 1932",                                                          
             "sjr 241 sjr 1110 sjr 1342 sjr 1822" )

df <- data.frame(character, numbers, output)
df

> df
  character            numbers                              output
1        ab               2823                            ab 2823
2       acr               2093                           acr 2093
3        sb                651                             sb 651
4        ab           876 1604                     ab 876 ab 1604
5        ab      772 1604 1932             ab 772 ab 1604 ab 1932
6       sjr 241 1110 1342 1822 sjr 241 sjr 1110 sjr 1342 sjr 1822

Any code you can provide to help would be greatly appreciated! Thank you!

CodePudding user response:

mapply to loop across the two data sources, and paste them together:

df$output <- mapply(paste, df$character, strsplit(df$numbers, "\\s "), collapse=" ")
df
#  character            numbers                             output
#1        ab               2823                            ab 2823
#2       acr               2093                           acr 2093
#3        sb                651                             sb 651
#4        ab           876 1604                     ab 876 ab 1604
#5        ab      772 1604 1932             ab 772 ab 1604 ab 1932
#6       sjr 241 1110 1342 1822 sjr 241 sjr 1110 sjr 1342 sjr 1822
  • Related