1

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

1

1 Answer 1

1

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"))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.