gpt4 book ai didi

r - 将字符串作为参数名称/值对传递给 R 函数

转载 作者:行者123 更新时间:2023-12-04 16:06:50 24 4
gpt4 key购买 nike

我想使用字符串 (s) 将其作为参数的名称/值对传递给函数。Test1 显示了我想要实现的目标。在 Test2 中,R 不调用 getInfo(PHONE_NUMBER = 123456),而是根据参数顺序使用 getInfo(FULL_NAME = "PHONE_NUMBER = 123456")。我该如何改变它?

该字符串还可以包含我想解析的各种参数,例如,“PHONE_NUMBER = 123456,ZIP = 1234”


s <- "PHONE_NUMBER = 123456"
getInfo <- function(FULL_NAME = "", FIRST_NAME = "", LAST_NAME = "",
ZIP = "", PHONE_NUMBER = "") {
l <- as.list(match.call())
myNames <- names(unlist(l[c(2, length(l))]))
print(myNames)
myValues <- unlist(l[c(2, length(l))])
print(myValues)
searchString <- paste(myNames, myValues, sep = "=", collapse = "&")
searchString <- paste0("search?PHONE_NUMBER=", searchString)
}
# Test 1: Setting the paramter manually
getInfo(PHONE_NUMBER = 123456)
#> [1] "PHONE_NUMBER" "PHONE_NUMBER"
#> PHONE_NUMBER PHONE_NUMBER
#> 123456 123456
# Test2 : Attempt to pass string as name/value fails; R uses the complete string as the first paramter (FULL_NAME = "PHONE_NUMBER = 123456") instead
getInfo(s)
#> [1] "FULL_NAME" "FULL_NAME"
#> $FULL_NAME
#> s
#>
#> $FULL_NAME
#> s

最佳答案

我们可以创建一个环境并在环境中创建变量。然后将环境转换为列表,并将变量列表作为参数传递给函数。

要了解有关 R 环境的更多信息,请参阅此 link

没有字符串s

getInfo(PHONE_NUMBER = 123456)
do.call("getInfo", list(PHONE_NUMBER = 123456))
# [1] "PHONE_NUMBER" "PHONE_NUMBER"
# PHONE_NUMBER PHONE_NUMBER
# 123456 123456

带有包含单个参数的字符串 s

s <- "PHONE_NUMBER = 123456"
myenv <- new.env() # create new environment
eval(parse(text = s), envir = myenv) # create variables inside environment using string s
ls(name = myenv) # list all variables inside the environment
# [1] "PHONE_NUMBER"
myenv$PHONE_NUMBER
# [1] 123456
do.call("getInfo", as.list.environment(myenv)) # call the function by passing the arguments which is obtained by converting environment into list
# [1] "PHONE_NUMBER" "PHONE_NUMBER"
# PHONE_NUMBER PHONE_NUMBER
# 123456 123456

对于包含多个参数的字符串 s - 将适用于单个或多个参数

s <- "PHONE_NUMBER = 123456, ZIP = 1234"
s <- unlist(strsplit(s, split = ",", fixed = TRUE)) # split string s using comma separator
s
# [1] "PHONE_NUMBER = 123456" " ZIP = 1234"
myenv <- new.env()
eval(parse(text = s), envir = myenv)
ls(name = myenv)
# [1] "PHONE_NUMBER" "ZIP"
do.call("getInfo", as.list.environment(myenv))
# [1] "ZIP" "PHONE_NUMBER"
# ZIP PHONE_NUMBER
# 1234 123456

关于r - 将字符串作为参数名称/值对传递给 R 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48379920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com