How to split a number into digits in R

后端 未结 7 611
花落未央
花落未央 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:23

    This should work:

    df <- cbind(do.call(rbind, strsplit(gsub('(.)(..)(...)', '\\1 \\2 \\3', paste(df[,1])),' ')), df[,-1]) # You need that paste() there because gsub() works only with text.
    

    Or with substr()

    df <- cbind(ID1=substr(df[, 1],1,1), ID2=substr(df[, 1],2,3), ID3=substr(df[, 1],4,6), df[, -1])
    

提交回复
热议问题