我想使用与 doParallel 后端一起运行的 foreach 每个循环来从带有 RMySql 包的 MySQL 数据库中获取推文。
我为要查询的每个用户 ID 创建一个到数据库的连接,然后我从该用户那里获得每条推文,分 200 批。如果批量大小为 0(因此没有更多推文),我会查询下一个用户 ID。
我想将信息存储在一个名为 tweets 的数据框中,该数据框中包含表示推文中标签数量的列和包含日期的列。对于每条推文,我都想知道它有多少标签,以及它是在哪个月份创建的。然后我想将数据框中的数字增加 1。
那么如何为数据框中的每条推文编写结果呢?
我一开始的数据框:
| dates | zero_ht | one_ht | two_ht | three_ht | four_ht | five_ht |
|----------|---------|--------|--------|----------|---------|---------|
| 01/01/13 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/02/13 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/03/13 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/04/13 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/05/13 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/06/13 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/07/13 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/08/13 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/09/13 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/10/13 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/11/13 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/12/13 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/01/14 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/02/14 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/03/14 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/04/14 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/05/14 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/06/14 | 0 | 0 | 0 | 0 | 0 | 0 |
| 01/07/14 | 0 | 0 | 0 | 0 | 0 | 0 |
我的代码:
x<- foreach(i=1:nrow(ids) ,.packages=c("DBI", "RMySQL"),.combine=rbind ) %dopar% {
con <- dbConnect(MySQL(), *CREDENTIALS*)
start <- 0
length <- 1
while(length > 0)
{
query <- *QUERY*
data <- dbGetQuery(con, query)
length <- nrow(data)
#print(paste("Starting at ",start,sep=""))
for(j in 1:length)
{
if(length==0)
{
}
else{
#get the number of hashtags used
number <- nchar((gsub("[^#]","",data$message[j])))
#get the date the tweet was created
date <- paste(format(as.Date(data$created_at[j]), "%Y-%m"),"-01",sep="")
# just use it when there are less than 5 hashtags
if(number < 5)
{
if(number==0)
{
tweets[tweets$dates==date,2] <- tweets[tweets$dates==date,2]+1
}
else{
tweets[tweets$dates==date,number+1] <- tweets[tweets$dates==date,number+1]+1
}
}
}
}
#increase the start by 200; to get the next 200 tweets
start <- start + 200
}
data.frame(date=date,number=number)
dbDisconnect(con)
}