R语言 如何使用表达式作为'c()'的键?

lh80um4z  于 2023-01-18  发布在  其他
关注(0)|答案(2)|浏览(190)

在R中,我可以在c()的值中放置一个连接表达式,如下所示:

c(
  foo = paste("first", "second", "third")
)

但是我不能用键来做这些(因为它不是字符串)

c(
  paste("first", "second", "third") = "foo"  # Error: unexpected '='
)

有什么办法吗?

x6yk4ghg

x6yk4ghg1#

使用setNames,因为=不允许对lhs上的表达式求值

setNames("foo", paste("first", "second", "third"))
first second third 
             "foo"

或者另一个选项是eval/parse,但最好使用setNamesnames<-

eval(parse(text = paste('c(', 
    dQuote(paste('first', 'second', 'third'), FALSE), '= "foo")')))
first second third 
             "foo"

尽管dplyr::lst可以用:=来实现这一点,所以如果我们需要一个命名向量,那么就创建一个命名列表和unlist

library(dplyr)
unlist(lst(!! paste("first", "second", "third") := "foo"))
first second third 
             "foo"
zkure5ic

zkure5ic2#

考虑到"names"attr属性,可以实现所需的对称行为。

`attr<-`("foo", "names", paste("first", "second", "third"))
# first second third 
#              "foo" 

`attr<-`(paste("first", "second", "third"), "names", "foo")
#                  foo 
# "first second third"

* 编辑 *

处理您的评论:
文档?httr::add_headers声明 .headers可以是一个命名的字符向量”。 因此,如果您有一个列表hnames(您的“变量”),您可以在列表上lapplypaste,并使用attr<-命名values

httr::add_headers(.headers=`attr<-`(values, "names", lapply(hnames, paste, collapse='-')))
# <request>
# Headers:
# * Origin: http://fiddle.jshell.net
# * Accept-Encoding: gzip, deflate
# * Accept-Language: en-US,en;q=0.8
# * User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36
# * Content-Type: application/x-www-form-urlencoded; charset=UTF-8
# * Accept: */*
# * Referer: http://fiddle.jshell.net/_display/
# * X-Requested-With: XMLHttpRequest
# * Connection: keep-alive

当然,@akrunsetNames解决方案可能更简单:

httr::add_headers(.headers=setNames(values, lapply(hnames, paste, collapse='-')))
# <request>
# Headers:
# * Origin: http://fiddle.jshell.net
# * Accept-Encoding: gzip, deflate
# * Accept-Language: en-US,en;q=0.8
# * User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36
# * Content-Type: application/x-www-form-urlencoded; charset=UTF-8
# * Accept: */*
# * Referer: http://fiddle.jshell.net/_display/
# * X-Requested-With: XMLHttpRequest
# * Connection: keep-alive
  • 数据:*
hnames <- list("Origin", c("Accept", "Encoding"), c("Accept", "Language"
), c("User", "Agent"), c("Content", "Type"), "Accept", "Referer", 
    c("X", "Requested", "With"), "Connection")
values <- c("http://fiddle.jshell.net", "gzip, deflate", "en-US,en;q=0.8", 
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36", 
"application/x-www-form-urlencoded; charset=UTF-8", "*/*", "http://fiddle.jshell.net/_display/", 
"XMLHttpRequest", "keep-alive")

相关问题