Anurag H
Anurag H

Reputation: 1029

Concatenate factors in R

I have a set of factors as follows:

str(range)
int[1:2] 4 5
set=collection$words[range]
set
[1] movie X    
Levels: hated I movie the X
print(paste("Talking about",set))

"Talking about movie"  "Talking about X"

What I want to achieve is whatever be the number of strings in the collection 'set' should appear 'concatenated' as one string when printing, example here when I run the print(paste()) command it should print

Talking about movie X

and this should be dynamic for any number of strings in the set collection.

Upvotes: 0

Views: 485

Answers (1)

akrun
akrun

Reputation: 887611

Based on the code showed, 'set' is a vector of words derived based on the numeric index in 'range'. To concatenate the elements in 'set', first paste it together with collapse=' ').

paste('Talking about', paste(set, collapse=' '))
#[1] "Talking about movie X"

data

set <- factor(c('movie', 'X'))

Upvotes: 3

Related Questions