使用 tidyverse 提取列中的数字并追加到新列
可以使用 tidyverse 中的 mutate() 和 str_extract_all() 函数来实现:
library(tidyverse)
# 示例数据
df <- data.frame(
X = c('abc123', '456de', 'gh789'),
stringsAsFactors = FALSE
)
# 提取数字
df_new <- df %>%
mutate(X_digits = str_extract_all(X, '\d+') %>%
map_chr(~ ifelse(length(.) > 0, paste(., collapse = ','), NA)))
df_new
输出结果:
X X_digits
1 abc123 123
2 456de 456
3 gh789 789
其中,str_extract_all() 函数使用正则表达式 \d+ 提取 X 列中的所有数字,然后使用 map_chr() 函数将每个数字向量转换为字符向量,并以逗号隔开。如果 X 列中不存在数字,则新列中对应的值为 NA。
原文地址: http://www.cveoy.top/t/topic/nOeK 著作权归作者所有。请勿转载和采集!