split - splitting comma separated mixed text and numeric string with strsplit in R -


i have many strings of form name1, name2 , name3, 0, 1, 2 or name1, name2, name3 , name4, 0, 1, 2 , split vector 4 elements first 1 whole text string of names. problem strsplit doesn't differenciate between text , numbers , split string 5 elements in first case , 6 elements in second example. how can tell r dynamically skip text part of string variable number of names?

you have 2 main options:
(1) grep numbers, , extract those.
(2) split on comma, coerce numeric , check nas

i prefer second

splat <- strsplit(x, ",")[[1]] numbs <- !is.na(suppresswarnings(as.numeric(splat)))  c(paste(splat[!numbs], collapse=","), splat[numbs]) # [1] "name1, name2 , name3" " 0" " 1" " 2" 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -