How to split a number into digits in R

后端 未结 7 615
花落未央
花落未央 2021-02-01 17:38

I have a data frame with a numerical ID variable which identify the Primary, Secondary and Ultimate Sampling Units from a multistage sampling scheme. I want to split the origina

7条回答
  •  孤独总比滥情好
    2021-02-01 18:32

    If you don't want to convert to character for some reason, following is one of the way to achieve what you want

    DF <- data.frame(ID = c(501901, 501902), var1 = c("a", "b"), var2 = c("c", "d"))
    
    result <- t(sapply(DF$ID, function(y) {
        c(y%/%1e+05, (y - y%/%1e+05 * 1e+05)%/%1000, y - y%/%1000 * 1000)
    }))
    
    
    DF <- cbind(result, DF[, -1])
    
    names(DF)[1:3] <- c("ID1", "ID2", "ID3")
    
    DF
    ##   ID1 ID2 ID3 var1 var2
    ## 1   5   1 901    a    c
    ## 2   5   1 902    b    d
    

提交回复
热议问题