3

我有一个帧数据“testData”如下:

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

而且我还有另一个帧数据“addr”如下:

id   addr
 1   America
 2   Canada
 3   China
 4   Japan

那么我如何使用grepl,sapply或 R 中的任何其他有用函数将数据生成如下:

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
4

3 回答 3

0

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

testData$addr <- gsub("I came from ", testData$content)
于 2015-01-30T06:47:15.060 回答
0

这可以解决问题:

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
})
于 2015-01-30T06:54:11.693 回答
0

这是使用一些tidyverse功能的粗略解决方案:

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
于 2018-07-12T02:07:46.520 回答