从自由文本输入中提取数字和总和数字,添加到 df
Exctract number and sum number from free text input, add to df
我有一个数据框,其中有一列包含关于受教育年限的自由文本条目。我想从自由文本条目中提取所有数字并对它们求和。
示例:data_en$educationTxt[1]给出“6小学10高中”
使用以下代码,我可以提取两个数字并将它们相加。
library(stringr)
x <- as.numeric(str_extract_all(data_en$education[1], "[0-9A]+")[[1]])
x <- as.vector(x)
x <- sum(x)
但是,理想情况下,我希望对所有自由文本条目(即每一行)执行此操作,然后将结果添加到每行的数据框中(即在诸如 data_en$educationNum 的变量中)。我对如何进行有点困惑。
您只需要 map
覆盖 str_extract_all
的输出
x <- c('300 primary 1 underworld', '6 secondary 9 dungeon lab')
library(purrr)
map_dbl(str_extract_all(x, '\d+'), ~ sum(as.numeric(.)))
# [1] 301 15
您可以使用 sapply
:
data_en$educationNum <- sapply(str_extract_all(data_en$education, "[0-9]+"),
function(i) sum(as.numeric(i)))
data_en
# education educationNum
# 1 6 primary school 10 highschool 16
# 2 10 primary school 2 highschool 12
# 3 no school 0
数据
data_en <- data.frame(education = c("6 primary school 10 highschool",
"10 primary school 2 highschool",
"no school"))
我有一个数据框,其中有一列包含关于受教育年限的自由文本条目。我想从自由文本条目中提取所有数字并对它们求和。
示例:data_en$educationTxt[1]给出“6小学10高中”
使用以下代码,我可以提取两个数字并将它们相加。
library(stringr)
x <- as.numeric(str_extract_all(data_en$education[1], "[0-9A]+")[[1]])
x <- as.vector(x)
x <- sum(x)
但是,理想情况下,我希望对所有自由文本条目(即每一行)执行此操作,然后将结果添加到每行的数据框中(即在诸如 data_en$educationNum 的变量中)。我对如何进行有点困惑。
您只需要 map
覆盖 str_extract_all
x <- c('300 primary 1 underworld', '6 secondary 9 dungeon lab')
library(purrr)
map_dbl(str_extract_all(x, '\d+'), ~ sum(as.numeric(.)))
# [1] 301 15
您可以使用 sapply
:
data_en$educationNum <- sapply(str_extract_all(data_en$education, "[0-9]+"),
function(i) sum(as.numeric(i)))
data_en
# education educationNum
# 1 6 primary school 10 highschool 16
# 2 10 primary school 2 highschool 12
# 3 no school 0
数据
data_en <- data.frame(education = c("6 primary school 10 highschool",
"10 primary school 2 highschool",
"no school"))