我需要能够从数据框的各个列中提取值并将它们插入到函数/循环中的特定位置。
我的数据框:它是“新起点”(新员工)的 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")
期望的结果如下:
我知道我需要使用一个应用函数或一个循环来运行数据框并准备 POST 请求的列表/正文,但我不确定如何将它们拼凑在一起!任何帮助将不胜感激,谢谢大家。
您可以将代码放入一个函数中,并使用任何 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
请求的输出是一个数据帧,您可能需要do.call(rbind, result)
将结果合并到一个数据帧中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句