数据框架和文本挖掘

问题描述 投票:-1回答:2
library(stringr)
data<-data.frame(id=c(1,2,3), 
          text=c("This is (2020) text; mining exercise (1999)","Text analysis (1975) is; bit confusing (2012)","Hint (1998) on; this text (2007) analysis?"))

a <- b <- list()
mm <- data.frame(a=NA,b=NA)
for(i in 1:length(data$text)){
   a[[i]] <- lengths(strsplit(as.character(data$text[i]),";"))
   b[[i]] <- str_count(data$text[i], "\\(19[0-9]{2}\\)|\\(20[0-9]{2}\\)")
}

我得到的输出:

# mm
    a     b
1  NA     NA

为什么我没有为数据帧mm的每一行获取相应的值?该代码也没有错误。

预期输出:

# mm
   a   b
1  2   2
2  2   2
3  2   2
r text stringr
2个回答
1
投票

循环完成后,您会得到两个列表,ab以及预期的输出:

a
[[1]]
[1] 2

[[2]]
[1] 2

[[3]]
[1] 2

但是您永远不会将这些值分配给data.frame

mm <- data.frame(a=unlist(a),b=unlist(b))
mm
  a b
1 2 2
2 2 2
3 2 2

0
投票

带有tidyverse的选项

library(dplyr)
library(stringr)
library(purrr)
data %>% 
   transmute(out = str_split(text, ";")) %>% 
   transmute(a = lengths(out),
       b = lengths(map(out, ~ str_extract(.x, "(?<=(19|20))[0-9]{2}\\b"))))
#  a b
#1 2 2
#2 2 2
#3 2 2
© www.soinside.com 2019 - 2024. All rights reserved.