Divide a character by more than 1 word

I have the following character:

endvotes <- "Yes106No85EH2NT6ES0P1"

I would like to get data.framelike this

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

I know how to break each of them, for example:

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

yes
[1] 106

I think that one of the possibilities would be to divide by position, but the numbers (one, two or three digits) are not always the same, so I would like to separate the answers (yes, no, etc.). Of course, I could do this for each answer (as indicated above), but I'm sure there is a more elegant way. Can someone tell me how this is done beautifully? Thanks

+4
source share
4 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
+3
source

. stringi, (, , ):

require(stringi)
stri_split_charclass(str=endvotes,"\\p{N}",omit_empty=T)[[1]]
## [1] "Yes" "No"  "EH"  "NT"  "ES"  "P"  
stri_split_charclass(str=endvotes,"\\p{L}",omit_empty=T)[[1]]
## [1] "106" "85"  "2"   "6"   "0"   "1"  

str - , \p{N} \p{L} - , (N , L ). omit_empty "" - .

+3

, , , , :

([a-zA-Z]+)([0-9]+)

, . , .

+2

regex ..

strsplit(endvotes, split = "(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])", perl = T)
## [[1]]
##  [1] "Yes" "106" "No"  "85"  "EH"  "2"   "NT"  "6"   "ES"  "0"   "P"   "1"  
##

S <- strsplit(endvotes, split = "(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])", perl = T)[[1]]
res <- data.frame(t(S[seq_along(S)%%2 == 0]))
names(res) <- t(S[seq_along(S)%%2 == 1])
res
##   Yes No EH NT ES P
## 1 106 85  2  6  0 1  

res <- data.frame(t(regmatches(endvotes, gregexpr("[0-9]+", endvotes))[[1]]))
names(res) <- t(regmatches(endvotes, gregexpr("[A-Za-z]+", endvotes))[[1]])
res
##   Yes No EH NT ES P
## 1 106 85  2  6  0 1
+2

Source: https://habr.com/ru/post/1536910/


All Articles