简体   繁体   English

在 R 的函数中传递 arguments

[英]Passing arguments in functions in R


So I'm trying to create a function which will take an argument from a list and return it into a dataframe. 所以我正在尝试创建一个 function 它将从列表中获取一个参数并将其返回到 dataframe 中。 So far I got close with this sample code, but i've become stuck for a few weeks now. 到目前为止,我已经接近了这个示例代码,但我已经被困了几个星期了。
 # list of pets pets = list("cats", "dogs") # comment link search_url = paste("https://duckduckgo.com/?q=", pets[]) # empty data frame for the pets petsX <- data.frame() # function for x in pets getSearch <- function(x) { petsX <- ( search_url [x] ) } getSearch(1) # I want this to be: # https://duckduckgo.com/?q=cats

Any help or guidance in the right direction would be truly appreciated.任何正确方向的帮助或指导将不胜感激。

I am not sure why you need the petsX dataframe at all.我不知道你为什么需要petsX dataframe。 You already have all search terms in the list.您已经拥有列表中的所有搜索词。 It would probably be better if you store the results of the function in dataframe when you use it.如果在使用时将 function 的结果存储在 dataframe 中可能会更好。

# list of pets
pets = list("cats", "dogs")

# comment link
search_url = paste("https://duckduckgo.com/?q=", pets, sep = "")

# function for x in pets
getSearch <- function(x) {
  search_url[[x]]
}

getSearch(1)
#> [1] "https://duckduckgo.com/?q=cats"
getSearch(2)
#> [1] "https://duckduckgo.com/?q=dogs"

Created on 2021-02-22 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2021 年 2 月 22 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM