【发布时间】:2019-01-29 12:24:18
【问题描述】:
给定一个样本df:
df <- structure(list(test_id = c("123-456789123", "785-525135627",
"6545646545665456", "988898-65464654646464664", "987-656546464", "666-654564654"
)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))
我想将上面的列分成 2 列:
- id 的最后 N 个字符(比如 8 个)
- 左前缀
例如给定N = 8:
987-656546464 ---> split to: postfix prefix
56546464 987-6
我已经尝试过单独的功能来做到这一点:
separate(df, col = test_id, into = c("prefix", "postfix"), sep = "(.{8}$)", convert = T)
但它没有给我第二部分。
请指教。
【问题讨论】:
-
您是否尝试过来自库
stringr的str_sub? -
试试
separate(df, col = test_id, into = c("prefix", "postfix"), sep = 8, convert = TRUE) -
@Sotos 试过了,但后缀是空列...
-
哦,我没注意到最后 8个字符。
-
@Sotos 你帮了很多忙。也许你可以解释一下
"\\d(?=\\d{8,})"正则表达式?