Reputation: 861
Given such a character vector:
someVector <- c('sports node 1 s',
'music node 1 s',
'painting node 1 s',
'music node 3 s',
'painting node 3 s',
'sports node 3 s',
'painting node 4 s',
'music node 4 s',
'sports node 7 s'
)
I need to create 3 vectors from the above vector based on the first word of each element in the vector. For example: if the element starts with the word "music" it should be appended to a vector named "music". When manually done this is easy. However, I have a big list and there are hundreds of these categories. Only 3 categories (music, sports, painting) are present in the given example above. When dealing with the big list, I cannot manually create empty vectors and populate them by a condition. I was wondering if there is a way to create these vectors in a loop and populate them without manually defining them. The expected output is:
sports <- c('sports node 1 s','sports node 3 s','sports node 7 s')
music <- c('music node 1 s','music node 3 s','music node 4 s')
painting <- c('painting node 1 s','painting node 3 s','painting node 4 s')
Upvotes: 0
Views: 57
Reputation: 10761
Here's a way to split up the vector, resulting in a named list:
split(someVector, gsub(pattern = "\\s.*", "", someVector))
# $music
# [1] "music node 1 s" "music node 3 s" "music node 4 s"
# $painting
# [1] "painting node 1 s" "painting node 3 s" "painting node 4 s"
# $sports
# [1] "sports node 1 s" "sports node 3 s" "sports node 7 s"
Straightforward to create the vectors:
split_list <- split(someVector, gsub(pattern = "\\s.*", "", someVector))
music <- split_list$music
painting <- split_list$painting
sports <- split_list$sports
Upvotes: 1