How to split a number into digits in R

后端 未结 7 703
花落未央
花落未央 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

    Yet another alternative is to re-read the first column using read.fwf and specify the widths:

    cbind(read.fwf(file = textConnection(as.character(df[, 1])), 
                   widths = c(1, 2, 3), colClasses = "character", 
                   col.names = c("ID1", "ID2", "ID3")), 
          df[-1])
    #   ID1 ID2 ID3 var1 var2 var3 var4  var5
    # 1   5  01 901    9 SP.1    1    W 12.10
    # 2   5  01 901    9 SP.1    2    W 17.68
    

    One advantage here is being able to set the resulting column names in a convenient manner, and ensure that the columns are characters, thus retaining any leading zeroes that might be present.

提交回复
热议问题