R for循环功能

时间:2017-01-25 08:37:40

标签: r for-loop

编辑:我有以下代码。本质上,它是从数据框中获取函数的图像。我无法弄清楚执行for循环的最佳方法是什么,或者是否有更好的选择。最终目标是到达DF_ALL。数据框有超过100个图像。所以,下面的解决方案并不是最优雅的。

# Part 1, Get some profile images from Twitter.

library(rtweet) #I'm not including the key here.

# Get a list of IDs
followers <- get_followers("TWITTER_HANDLE_HERE", n = 10)

# Get the complete Twitter profile for the 10 users
follower_profiles <- lookup_users(followers)

# Create new variable profile_full_url for image API 
follower_profiles$profile_full_url <- gsub("normal", "400x400", follower_profiles$profile_image_url)

# Part 2, Proceed image with API
library(Roxford)
visionkey = 'KEY_FROM_GOOGLE' 

# Run image tag function on the first image
DF1 <- getTaggingResponseURL(follower_profiles$profile_full_url[1], visionkey)
DF1$twitter_url <- follower_profiles$profile_full_url[1]

# Here is the result (Notice how it is show 3 rows. I don't why it is. Would prefer to have 1 row per image)
# name        confidence width height format                                                                 twitter_url
# tags      wall 0.999090671539307  <NA>   <NA>   <NA> http://pbs.twimg.com/profile_images/9999999999_400x400.jpg
# requestId <NA>              <NA>  <NA>   <NA>   <NA> http://pbs.twimg.com/profile_images/9999999999_400x400.jpg
# metadata  <NA>              <NA>   400    400   Jpeg http://pbs.twimg.com/profile_images/9999999999_400x400.jpg

# The problem is... there could be 100+ of images.
# I feel that a for loop could potentially be the solution. 

DF1 <- getTaggingResponseURL(follower_profiles$profile_full_url[1], visionkey)
DF1$twitter_url <- follower_profiles$profile_full_url[1]

DF2 <- getTaggingResponseURL(follower_profiles$profile_full_url[2], visionkey)
DF2$twitter_url <- follower_profiles$profile_full_url[2]

DF3 <- getTaggingResponseURL(follower_profiles$profile_full_url[3], visionkey)
DF3$twitter_url <- follower_profiles$profile_full_url[3]

DF_ALL<-rbind(DF1,DF2,DF3)

2 个答案:

答案 0 :(得分:3)

一个网址的功能。

foo <- function(x) {
  DF <- getTaggingResponseURL(x, visionkey)
  DF$twitter_url <- x
  DF
}

foo应用于向量follower_profiles$profile_full_urlrbind结果。

DF_ALL <- do.call(rbind, lapply(follower_profiles$profile_full_url, foo))

可能这个也可以,但我不确定,因为我不知道数据的结构。

DF_ALL <- sapply(follower_profiles$profile_full_url, foo)

答案 1 :(得分:2)

试试这个:

for (i in 1:nrow(follower_profiles)) {
    DF <- getTaggingResponseURL(follower_profiles$profile_full_url[i], visionkey)
    DF$twitter_url <- follower_profiles$profile_full_url[i]
    if (i == 1) {
        DF_ALL <- DF
    } else {
        DF_ALL <- rbind(DF_ALL,DF)
    }
}