Can I use separate () or extract () from tidyr to split a variable length numeric value into its component digits?

I have a data frame with ~ 300 observations, each of which is associated with a numerical code, which I want to break down into its components. The code variable is either a 3 or 4-digit integer aligned with its last digit, and so my desired result would look something like this:

code    d4 d3 d2 d1
 403  <NA>  4  0  3 
5123     5  1  2  3
 105  <NA>  1  0  5    

While I can see many ways to split the code using strsplit(base R) or stringr::str_split, I can hardly apply any of these operations to a data frame.

library(stringr)
as.integer(unlist(str_split(5123, ""))[1]) # returns 5, the first digit - correct
as.integer(rev(unlist(str_split(5123, "")))[1]) # returns 3, the last digit - correct

But believable (to me) operation

libray(dplyr)
df <- data.frame(code = c(403, 5123, 105))
df <- df %>% 
  mutate(
    last = as.integer(rev(unlist(str_split(df$code,"")))[4])
  )

returns

> df
  code last
1  403    3
2 5123    3
3  105    3

Clearly, my understanding of how lists and atomic vectors are handled within data frames is lacking ...

, separate(), extract() tidyr . , tidyr::separate() , :

library(tidyr)
dfsep <- data.frame(code = c(" 4 0 3", "5 1 2 3", " 1 0 5"))
dfsep <- dfsep %>% 
  separate(
    code, c("d4", "d3", "d2", "d1"), fill =  "right", remove = FALSE
    )

dfsep
     code d4 d3 d2 d1
1   4 0 3     4  0  3
2 5 1 2 3  5  1  2  3
3   1 0 5     1  0  5

; tidyr::separate()

df <- data.frame(code = c(403, 5123, 105))
df <- df %>% 
  separate(
    code, c("d4", "d3", "d2", "d1"), fill =  "right", remove = FALSE
  )

df
  code   d4   d3   d2   d1
1  403  403 <NA> <NA> <NA>
2 5123 5123 <NA> <NA> <NA>
3  105  105 <NA> <NA> <NA>

tidyr::extract() , , , , 3, 4 :

dfext <- data.frame(code = c(403, 5123, 105))
dfext <- dfext %>% 
  extract(
    code, c("d4", "d3", "d2", "d1"), "(.)(.)(.)(.)", remove = FALSE
    ) 

dfext
  code   d4   d3   d2   d1
1  403 <NA> <NA> <NA> <NA>
2 5123    5    1    2    3
3  105 <NA> <NA> <NA> <NA>

, , ...

StackOverflow, separate(), extract(), , . , .

, !

P.S. , . , : , , , (, 1 5), , , , , J1, J2,... J5 , ( ) ( , ). FINA

+4
4

stri_list2matrix stringi strsplit

n <- max(nchar(df$code)) #get the maximum number of characters
fmt <- paste0('%', n, 'd') #create a format for the `sprintf`
library(stringi)
#the list output from `strsplit` can be coerced to `matrix` using
#stri_list2matrix.
d1 <- stri_list2matrix(strsplit(sprintf( fmt, df$code), ''), byrow=TRUE)
#But, the output is character class, which we can convert to 'numeric' 
m1 <- matrix(as.numeric(d1), ncol=ncol(d1), nrow=nrow(d1))
m1
#     [,1] [,2] [,3] [,4]
#[1,]   NA    4    0    3
#[2,]    5    1    2    3
#[3,]   NA    1    0    5

dfsep

v1 <- gsub('\\s+', '', dfsep$code)
n <- max(nchar(v1))
fmt <- paste0('%', n, 's')
d1  <- stri_list2matrix(strsplit(sprintf(fmt, v1), ''), byrow=TRUE)
m1 <- matrix(as.numeric(d1), ncol=ncol(d1), nrow=nrow(d1))
m1
#     [,1] [,2] [,3] [,4]
#[1,]   NA    4    0    3
#[2,]    5    1    2    3
#[3,]   NA    1    0    5

cbind

cbind(dfsep, m1)

.

+1

,

f <- function(df) {
  f <- tempfile()
  df$ccode <- gsub('\\s+', '', df$code)
  cat(file = f, sprintf('%4s', gsub('\\s+', '', df$ccode)), sep = "\n")
  cbind(code = df$code, read.fwf(f, widths = rep(1, max(nchar(df$ccode)))))
}

df <- data.frame(code = c(403, 5123, 105))
f(df)
#   code V1 V2 V3 V4
# 1  403 NA  4  0  3
# 2 5123  5  1  2  3
# 3  105 NA  1  0  5

dfsep <- data.frame(code = c(" 4 0 3", "5 1 2 3", " 1 0 5"))
f(dfsep)
#      code V1 V2 V3 V4
# 1   4 0 3 NA  4  0  3
# 2 5 1 2 3  5  1  2  3
# 3   1 0 5 NA  1  0  5
+1

The regular expression should be "(.)? (.) (.) (.)"

? to use for an element occurs zero or once

dfext %>% extract(code, c('d1','d2','d3','d4'), "(.)?(.)(.)(.)")
d1 d2 d3 d4
1 <NA>  4  0  3
2    5  1  2  3
3 <NA>  1  0  5
+1
source

Simple basic R solution

codes = c(403, 5123, 105)

# make all codes the same length
l = sapply(codes, nchar)
s = strrep(' ', max(l) - l)
new_codes = paste0(s, codes)

# split and combine into matrix
res = do.call(rbind, strsplit(new_codes, ''))

Reformat as needed:

res = data.frame(code=codes, res)
colnames(res) = c('code', 'd4', 'd3', 'd2', 'd1')

Output:

  code d4 d3 d2 d1
1  403     4  0  3
2 5123  5  1  2  3
3  105     1  0  5
0
source

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


All Articles