Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split character by more than 1 words

I have the following character:

endvotes <- "Yes106No85EH2NT6ES0P1"

I'd like to get a data.framelooking like this

    Yes    No   EH   NT   ES  P
    106    85   2    6    0   1

I know how to split each one of those, for example like this:

yes <- unlist(str_split(end_votes, "\\No"))[1]
yes <- as.integer(unlist(str_split(yes, "Yes"))[2])

yes
[1] 106

I guess one possibility would be to split by positions, but the numbers (one, two or three digits) are not always the same, therefore I'd like to split by the answers (yes, no, etc.). Of course I could do this for every answer (as above) but I'm sure there is a more elegant way. Can anyone tell me how this is done nicely? Thanks

like image 402
Thomas Avatar asked Dec 26 '22 10:12

Thomas


1 Answers

endvotes <- "Yes106No85EH2NT6ES0P1"

names <- strsplit(endvotes, "[[:digit:]]+")[[1]]
numbers <- strsplit(endvotes, "[[:alpha:]]+")[[1]][-1]

setNames(as.data.frame(t(as.numeric(numbers))), names)
#  Yes No EH NT ES P
#1 106 85  2  6  0 1
like image 75
Roland Avatar answered Jan 11 '23 23:01

Roland