Search code examples
rstrsplit

How to split a data frame column based on equal length into separate rows in R


enter image description here

Any help will be appreciated, Thanks.


Solution

  • Here is one base R option

    f <- function(v) Map(intToUtf8,split(utf8ToInt(v),ceiling(seq(nchar(v))/2)))
    q <- Vectorize(f)(mydf$V2)
    p <- rep(mydf$V1,lengths(q))
    mydfout <- data.frame(V1 = p,V2 = unlist(q),row.names = NULL)
    

    which gives

    > mydfout
       V1 V2
    1   1 ab
    2   1 cd
    3   1 ef
    4   2 ab
    5   2 cd
    6   3 bg
    7   3 hj
    8   4 kl
    9   5 ui
    10  5 lm
    

    Data

    mydf <- structure(list(V1 = 1:5, V2 = c("abcdef", "abcd", "bghj", "kl", 
    "uilm")), class = "data.frame", row.names = c(NA, -5L))