for(artist in 1:nrow(epop8)){
message(paste("Artist:", artist))
id = epop8$spotify_id[artist];
cur_showDate = epop8$ShowDate[artist]
dma_show = epop8$DMA_Region_Code[artist]
spotifySubset = na.omit(spotify[spotify$spotify_id == id,])
if(nrow(spotifySubset) == 0){
epop8$last6month[artist] = NA
next
}
monthsOfInterest_6 = epop8$ShowDate[artist] - 180:1
monthsOfInterest_12 = epop8$ShowDate[artist] - 365:1
epop8Subset6MO = unique(epop8[epop8$ShowDate %in% monthsOfInterest_6,
c("spotify_id", "DMA_Region_Code", "ShowDate")]) %>%
subset(., DMA_Region_Code == dma_show) %>% arrange(desc(ShowDate))
epop8Subset1Yr = unique(epop8[epop8$ShowDate %in% monthsOfInterest_12,
c("spotify_id", "DMA_Region_Code", "ShowDate")]) %>%
subset(., DMA_Region_Code == dma_show) %>% arrange(desc(ShowDate))
last6month = epop8Subset6MO[spotifySubset$relatedID %in% epop8Subset6MO$spotify_id,]
last12month = epop8Subset1Yr[spotifySubset$relatedID %in% epop8Subset1Yr$spotify_id,]
epop8$since_related_artist[artist] = ifelse(!nrow(last6month) && !nrow(last12month),
365,
as.double(cur_showDate - last6month$ShowDate[1]))
epop8$related_artist_count_6MO[artist] = nrow(last6month)
epop8$related_artist_count_12MO[artist] = nrow(last12month)
}
我只是试图将此for循环“转换”为并行化的foreach循环。我试图理解如何甚至接近foreach循环。我试过了
ntasks <- nrow(epop8)
pb <- tkProgressBar(max=nrow(epop8))
progress <- function(n) setTkProgressBar(pb, n)
opts <- list(progress=progress)
foreach(artist=1:nrow(epop8), .combine = combine,
.packages = "dplyr", .options.snow=opts) %dopar%{
...
}
其中“...”与上面的for循环中包含的完全相同的代码。现在,我知道这不是必须这样做的方法,但我不确定如何在foreach并行化循环中更新我的数据帧或子集我的数据帧。我已经浏览了互联网,但我开始认为foreach有点过头了。
以下是数据集的外观:
spotify = data.frame(artistName = "Bob", spotify_id = "abcd",
related = c("Al", "Bill", "Charles","Daniel"),
relatedID = c("1234", "efrd", "bcde", "fghi"))
epop8 = data.frame(id = c("abcd", "asdf", "robd", "1234"),
dma = c("654", "332", "489", "654"),
ShowDate = c("2017-10-08", "2011-10-04", "2012-10-01", "2017-08-01"))
所以在这里,当我们为Bob(epop8中的第一位艺术家)的DMA中的最后6个月和12个月分配epop8时,我们得知在过去的12个月中该节目中有一场比赛 - - Daniel于2017-08-01。
希望这一切都有道理,我真的很喜欢你对这个的帮助!