簡體   English   中英

遍歷列表以創建不同對象的函數

[英]Function that iterates through list to create different objects

我目前已經編寫了一個函數,在該函數中我將單獨瀏覽多個 twitter 句柄並根據該 twitter 用戶的姓氏命名一個對象。 例如:

f <- function() {
  dougjones <- rtweet::get_timeline('@SenDougJones', n = 50, max_id = NULL, home = FALSE, parse = TRUE, check = FALSE, token = token, include_rts = FALSE)
  bennet <- rtweet::get_timeline('@SenatorBennet', n = 50, max_id = NULL, home = FALSE, parse = TRUE, check = FALSE, token = token, include_rts = FALSE)
  blumenthal <- rtweet::get_timeline('@SenBlumenthal', n = 50, max_id = NULL, home = FALSE, parse = TRUE, check = FALSE, token = token, include_rts = FALSE)
}

我想通過創建用戶姓氏和他們的 twitter 句柄列表來簡化這一點,以創建一些看起來像這樣的代碼(如果代碼工作正常)

list <- list(
  handles(handle = 
  tibble(c('@SenDougJones','@SenatorBennet','@SenBlumenthal')),
  names(name = tibble(c('Jones','Bennet','Blumenthal')))

f <- function(list){
  for(i in seq_along(list$handles)){
  for(j in seq_along(list$names)){
   names[[j]] <- rtweet::get_timelines(list$handles[[i]],n=50,max_id=NULL,home=FALSE,parse=TRUE, check = FALSE, token = token,include_rts=FALSE) }}}

我知道這段代碼是錯誤的,因為我在運行它時得到 NULL。 我想知道我將如何去做這件事。 基本上我希望做的是通過 get_timeline() 函數迭代地輸入 twitter 句柄,並根據用戶的姓氏命名每次迭代中的對象。

我對使用循環有點陌生,所以我不知道這是語法問題還是什么,但我希望你們都能提出建議。 我該怎么做才能得到這個結果?

我不知道您到底在尋找什么,但以下內容應該可以解決問題。

last.names <- c('Jones','Bennet','Blumenthal')
twitter.handles <- c('@SenDougJones','@SenatorBennet','@SenBlumenthal')

my.list <- list(last.names = last.names,
                twitter.handles = twitter.handles,
                indexes = seq_along(last.names))

my.list$twitter.timeline <- lapply(my.list$indexes,
       FUN = function(index) {
         print(paste(my.list$last.names[[index]], my.list$twitter.handles[[index]], sep = ";"))
         
         twitter.timeline <- rtweet::get_timelines(my.list$twitter.handles[[index]],
                                                                   n=50,
                                                                    max_id=NULL,
                                                                    home=FALSE,
                                                                    parse=TRUE,
                                                                    check = FALSE,
                                                                    token = token,
                                                                    include_rts=FALSE)

           return(twitter.timeline)
       })


哼!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM