简体   繁体   中英

Create multiple vectors out of a vector based on a pattern R

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')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM