Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R数据帧中文本的矢量化搜索_R_Twitter_Dataframe - Fatal编程技术网

R数据帧中文本的矢量化搜索

R数据帧中文本的矢量化搜索,r,twitter,dataframe,R,Twitter,Dataframe,我有一个数据框架“cities.df”,其中一列包含巴西的所有城市,另一列包含巴西各自的州 在另一个数据框“tweets.df”中,我有一个包含tweets的专栏,其中可能包含一些关于城市或州的参考 我想做的是在tweets.df中添加一个列,并对其位置进行“估计”,假设他在tweet上发布了关于圣保罗州某个城市的信息,那么他就位于圣保罗州 我是R新手,我能想到的唯一实现方法是在所有tweet上使用级联循环,然后在所有城市应用grep函数。但这似乎不是用R实现它的正确方法 for tweet i

我有一个数据框架“cities.df”,其中一列包含巴西的所有城市,另一列包含巴西各自的州

在另一个数据框“tweets.df”中,我有一个包含tweets的专栏,其中可能包含一些关于城市或州的参考

我想做的是在tweets.df中添加一个列,并对其位置进行“估计”,假设他在tweet上发布了关于圣保罗州某个城市的信息,那么他就位于圣保罗州

我是R新手,我能想到的唯一实现方法是在所有tweet上使用级联循环,然后在所有城市应用grep函数。但这似乎不是用R实现它的正确方法

for tweet in tweets
    for city in cities
        grep(city, tweet)
我想知道是否有一种更“矢量化”的方法来实现这一点


谢谢

好吧,你不需要重复这两个步骤。grep一次只能获取一个模式,但可以在向量中搜索结果。所以

for city in cities
    grep(city, tweets)

更合理一点。

这里有一种方法可以做到这一点。考虑<代码>城市< /代码>和<代码> twitts <代码>是从它们各自的数据帧中提取的向量。这些推特显然是虚构的,甚至不是文字。我只是通过采样字母并将它们粘贴在一起来创建它们。要在添加某些数据时更新

最后一行将返回包含
cities
列表中城市的tweet

> cities
# [1] "Belém"               "Belo Horizonte"      "Blumenau"           
# [4] "Brasília"            "Campinas"            "Curitiba"           
# [7] "Florianópolis"       "Fortaleza"           "Goiania"            
# [10] "Macáe"               "Manaus"              "Niteroi"            
# [13] "Porto Alegre"        "Recife"              "Rio de Janeiro"     
# [16] "Roraima"             "Salvador"            "Santo Andre"        
# [19] "Santos"              "São José dos Campos" "São Paulo"          
# [22] "Vitória"            
> tweets
# [1] "Niteroi rjzzfbymh wj fa elxbmyfk logeb"
# [2] "no city present in this sentence"      
# [3] "Vitória zl qxllds buoo fvclizxv zqf"   
# [4] "Rio de Janeiro n zaocj u ouo bck"      
# [5] "no city present in this sentence"      
> unlist(sapply(seq(cities), function(i){
      grep(cities[i], tweets, value = TRUE)
  }))
# [1] "Niteroi rjzzfbymh wj fa elxbmyfk logeb"
# [2] "Rio de Janeiro n zaocj u ouo bck"      
# [3] "Vitória zl qxllds buoo fvclizxv zqf"   

您似乎希望在tweet中添加一个列,根据tweet中提到的城市标识州。这有几个问题。首先,城市不是唯一的——也就是说,在不同的州可以有多个同名城市。因此,城市并不是唯一的国家标识。第二,可以通过多种方式识别城市。例如,巴西有四个不同的圣保罗,它们都可能以相同的方式被引用,特别是在推特中

São Paulo de Olivença
São Paulo do Potengi 
São Paulo das Missões
São Paulo 
尽管有所有这些保留,这里有一种附加城市和州名称的方法。该代码还处理了tweet中未提及任何城市的可能性

library(raster)
# this generates sample data - you have this already (??)
br   <- getData(country="BR",level=2)            # Brazil shapefile, admin level 2
# muni$NAME_1 has the state names; muni$NAME_2 has the city names
muni <- br@data                                  # ~5500 municipalities in Brazil
set.seed(1)                                      # for reproduceable example
cities <- muni[sample(1:nrow(muni),90),]$NAME_2  # 90 random cities in brazil
cities <- c(cities,rep("",10))                   # last 10% have no city mentioned
tweets <- sapply(1:100,function(i) paste("#random text",cities[i],"more random text"))

# you start here
result <- do.call(rbind,lapply(tweets,function(tweet) {
  indx <- sapply(muni$NAME_2, grepl, tweet,fixed=T) # all matching cities
  indx <- min(which(indx))                          # use only first match!!
  muni[indx,c("NAME_2","NAME_1")]                   # NAME_1 contains the state
}))
tweets <- data.frame(tweets,result)
head(tweets)
#                                                        tweets    NAME_2       NAME_1
# 1462                       #random text Piau more random text      Piau Minas Gerais
# 2048                     #random text Estiva more random text    Estiva Minas Gerais
# 1474 #random text Nova Esperança do Sudoeste more random text Esperança      Paraíba
# 4997                    #random text Monções more random text   Monções    São Paulo
# 1110                      #random text Goiás more random text     Goiás        Goiás
# 4941                    #random text Jumirim more random text   Jumirim    São Paulo
tail(tweets)
#                             tweets NAME_2 NAME_1
# NA4 #random text  more random text   <NA>   <NA>
# NA5 #random text  more random text   <NA>   <NA>
# NA6 #random text  more random text   <NA>   <NA>
# NA7 #random text  more random text   <NA>   <NA>
# NA8 #random text  more random text   <NA>   <NA>
# NA9 #random text  more random text   <NA>   <NA>
库(光栅)
#这将生成示例数据-您已经有了它(?)

br看一看
expand.grid
:类似于
sappy(expand.grid(tweets,cities),function(x,y)grep(x,y))
一般认为您将提供MWE。这意味着你尝试过的数据和实际代码:嗯,这是真的,向量上的grep将返回单词出现的索引,对吗?@user2402105。请参见
grep(“a”、c(“苹果”、“柠檬”、“香蕉”)
这就是我要找的。谢谢@用户2402105,如果这个或任何其他答案为你工作,请考虑接受它作为答案。你也从接受答案中受益,而不仅仅是接受回答的人。