Home > database >  Combining list string elements with R
Combining list string elements with R

Time:08-13

I have a list containing multiple strings in each list position (see below). As you can see, in each position of the list is two string values. I want to combine both strings so that they form one string and insert a symbol in between them.

print(my_list)

>> [[1]]
>> [1] "A" "B"    

>> [[2]]
>> [1] "C" "D" "E" "F"

>> [[3]]
>> [1] "G" "H"   
...

This would be my desired output..

print(my_list)

>> [[1]]
>> [1] "A   B"    

>> [[2]]
>> [1] "C   D   E   F"

>> [[3]]
>> [1] "G   H"   
...

So far (as a starting point) I have tried using "paste" in a for loop, like this..

for (i in my_list){
  print(paste(i, sep = " "))
}

This did not have the intended effect. It simply duplicated each list item and did not insert a anywhere. Here is the output..

print(my_list)

>> [1] "A" "B" 
>> [1] "A" "B"    

>> [2] "C" "D" "E" "F"
>> [2] "C" "D" "E" "F"

>> [3] "G" "H"  
>> [3] "G" "H"   
...

Any ideas? Cheers

CodePudding user response:

A simple lapply and paste does the trick:

lapply(mylist, function(x) paste(x, collapse = "   "))

# [[1]]
# [1] "A   B"
# 
# [[2]]
# [1] "C   D   E   F"
# 
# [[3]]
# [1] "G   H"

Sample Data:

mylist <- list(c("A", "B"),
     c("C", "D", "E", "F"),
     c("G", "H"))
  • Related