[英]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")
期望的結果如下:
我知道我需要使用應用 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.