簡體   English   中英

如何在 R 中循環遍歷帶有列表的數據框列?

[英]How to loop through data frame columns with lists as a result in R?

我需要能夠從數據幀的各個列中提取值並將它們插入到函數/循環中的特定 position 中。

我的數據框:它是“新員工”(新員工)的 df

id <- c(115, 115)
f_name <- c("John", "Mary")
l_name <- c("Black", "White")
gender <- c("Male", "Female")
s_date <- c("2021-03-01", "2021-03-01")
ns_df <- data.frame(id, f_name, l_name, gender, s_date)

這給出了以下內容:

   id f_name l_name gender     s_date
1 115   John  Black   Male 2021-03-01
2 115   Mary  White Female 2021-03-01

然后,我想獲取每個列值並將它們推送到 POST 請求中各自的位置,如下所示:

POST(url = myurl, config = authenticate(user = login,
                                        password = pw,
                                        type = "basic"),
     body = list(APIKey = my_key, # keep the same
                 Action = "CreateNewEmployee", # keep the same
                 EmployeeId = "id", # loop through ids
                 FirstName = "f_name", # loop through first names
                 LastName = "l_name", # look through last names
                 Gender = "gender", # loop through genders
                 StartDate = "s_date" #loop through start dates
       
     ),
     encode = "json")

期望的結果如下:

  1. 創建了一個帶有新啟動器的數據框(可以是 0 行,在這種情況下不執行任何操作)。 如果超過 0 行,則繼續
  2. 根據行數,啟動循環以遍歷每一行並提取屬性,以便每個屬性進入組成 POST 請求正文的列表的相應部分
  3. 為新的起始數據幀中的每一行發送一個 POST 請求

我知道我需要使用應用 function 或循環遍歷數據幀並准備 POST 請求的列表/正文,但我不完全確定如何將它們拼湊在一起,任何幫助將不勝感激. 謝謝你們。

您可以將代碼放入 function 並使用任何 apply 命令將其應用於每一行。

lapply(seq(nrow(ns_df)), function(i) {
  
  POST(url = myurl, config = authenticate(user = login,
                                          password = pw,
                                          type = "basic"),
       body = list(APIKey = my_key, # keep the same
                   Action = "CreateNewEmployee", # keep the same
                   EmployeeId = ns_df[i, "id"], # loop through ids
                   FirstName = ns_df[i, "f_name"], # loop through first names
                   LastName = ns_df[i, "l_name"], # look through last names
                   Gender = ns_df[i, "gender"], # loop through genders
                   StartDate = ns_df[i, "s_date"] #loop through start dates
                   
       ), encode = "json")
}) -> result

result

如果每個POST請求的 output 是 dataframe 您可能需要do.call(rbind, result)將結果合並到一個 dataframe 中。

暫無
暫無

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

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