简体   繁体   中英

Using grepl in R to match string

I have a frame data "testData" as follows:

id     content
 1     I came from China
 2     I came from America
 3     I came from Canada
 4     I came from Japan
 5     I came from Mars

And I also have another frame data "addr" as follows:

id   addr
 1   America
 2   Canada
 3   China
 4   Japan

Then how can I use grepl , sapply or any other useful function in R to generate data into as follows:

id   content               addr
 1   I came from China     China
 2   I came from America   America
 3   I came from Canada    Canada
 4   I came from Japan     Japan
 5   I came from Mars      Mars

看起来你只想复制列并删除“我来自”

testData$addr <- gsub("I came from ", testData$content)

This does the trick:

vec = addr$addr

testData$addr = apply(testData, 1, function(u){
    bool = sapply(vec, function(x) grepl(x, u[['content']]))
    if(any(bool)) vec[bool] else NA
})

Here is a crude solution using some tidyverse functions:

df1 <- read.table(text = "id     content
 1     'it is China'
 2     'She is in America now'
 3     'Canada is over there'
 4     'He comes from Japan'
 5     'I came from Mars'", header = TRUE, stringsAsFactors = FALSE)

df2 = read.table(text = "id   addr
 1   America
 2   Canada
 3   China
 4   Japan
 5   Mars", header = TRUE, stringsAsFactors = FALSE)

library(tidyverse)
crossing(df1, df2 %>% select(addr)) %>% # this creates a data frame of every possible content and add combination
  rowwise() %>% 
  filter(str_detect(content, add)) # str_detect is the same as grepl, though the arguments are reversed. This filters to only observations where addr is in content.

# A tibble: 5 x 3
     id content               addr   
  <int> <chr>                 <chr>  
1     1 it is China           China  
2     2 She is in America now America
3     3 Canada is over there  Canada 
4     4 He comes from Japan   Japan  
5     5 I came from Mars      Mars

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM