celestialgod

split string and numbers

Jul 3rd, 2019
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 0.84 KB | None | 0 0
  1. library(data.table)
  2. library(stringr)
  3. DT <- data.table(交易筆棟數 = c("土地1建物1車位2", "土地1建物1車位1", "土地1建物1車位0",
  4.                            "土地1建物1車位1", "土地1建物1車位1", "土地1建物1車位0"))
  5. col_names <- str_split(DT$交易筆棟數[1], "\\d+")[[1]][1L:3L]
  6. get_trade_unit_func <- function(x) {
  7.   temp <- str_match(x, "土地(\\d+)建物(\\d+)車位(\\d+)")
  8.   lapply(2L:4L, function(i) as.numeric(temp[ , i]))
  9. }
  10. DT[ , eval(col_names) := get_trade_unit_func(交易筆棟數)]
  11. DT
  12. #         交易筆棟數 土地 建物   車位
  13. # 1: 土地1建物1車位2    1    1     2
  14. # 2: 土地1建物1車位1    1    1     1
  15. # 3: 土地1建物1車位0    1    1     0
  16. # 4: 土地1建物1車位1    1    1     1
  17. # 5: 土地1建物1車位1    1    1     1
  18. # 6: 土地1建物1車位0    1    1     0
Advertisement
Add Comment
Please, Sign In to add comment