Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

r - Recognize patterns in column, and add them to column in Data frame

Got a column with 50 keywords:

Keyword1 
Keyword2
Keyword3
KeywordN=50

In addition I got a data frame with two columns: Title and Abstract.

Title                    Abstract 
Rstudio Keyword1        A interesting program language keyword2  
Python Keyword3         A interesting program keyword3 language 

I want to get an extra column (let's call it Keywords), where the keyword name will appear IF it is in the Title or Abstract, like this:

Title             Abstract                                   Keywords
Rstudio Keyword1 A interesting program language keyword2  Keyword1, keyword2
Python Keyword2  A interesting program keyword3 language  Keyword2, Keyword3

The only thing how I could 'solve' this, was by making a binary columns (if a pattern matched). (grepl function), but that was not the desired solution...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

in base R:

  • This handles punctuation, spaces, end/starts of lines.
  • Keywords can contain spaces and some punctuation (but not all)
  • keywords in new column keep the case of original keyword vector:

code

ind  <- sapply(paste0('(^|[ [:punct:]])',tolower(keywords),'($|[ [:punct:]])'),grep,tolower(paste(df$Title,df$Abstract)))
ind[lengths(ind)==0] <- NA # for cases where no keyword is found
ind2 <- do.call(rbind,Map(data.frame,keyword=keywords,i=ind))
ind3 <- aggregate(keyword ~ i,ind2,paste,collapse=', ')
df$keywords[ind3$i] <- ind3$keyword
df$keywords[is.na(df$keywords)] <- "" # replacing NAs with empty strings
#              Title                                Abstract           keywords
# 1 Rstudio Keyword1 A interesting program language keyword2 Keyword1, Keyword2
# 2  Python Keyword2 A interesting program keyword3 language Keyword2, Keyword3

data

keywords <- c("Keyword1", "Keyword2", "Keyword3")

df <- read.table(text="Title                    Abstract 
                 'Rstudio Keyword1'        'A interesting program language keyword2'  
                 'Python Keyword2'         'A interesting program keyword3 language'",h=T,strin=F)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...