gpt4 book ai didi

r - 在R中,如何在将对象发送到函数后获取对象的名称?

转载 作者:行者123 更新时间:2023-12-03 04:34:42 25 4
gpt4 key购买 nike

我正在寻找 get() 的反向操作。

给定一个对象名称,我希望直接从对象中提取代表该对象的字符串。

简单的示例,其中 foo 是我正在寻找的函数的占位符。

z <- data.frame(x=1:10, y=1:10)

test <- function(a){
mean.x <- mean(a$x)
print(foo(a))
return(mean.x)}

test(z)

将打印:

  "z"

我的解决方法(在我当前的问题中更难实现)是:

test <- function(a="z"){
mean.x <- mean(get(a)$x)
print(a)
return(mean.x)}

test("z")

最佳答案

旧的稀疏替代技巧:

a<-data.frame(x=1:10,y=1:10)
test<-function(z){
mean.x<-mean(z$x)
nm <-deparse(substitute(z))
print(nm)
return(mean.x)}

test(a)
#[1] "a" ... this is the side-effect of the print() call
# ... you could have done something useful with that character value
#[1] 5.5 ... this is the result of the function call

编辑:使用新的测试对象运行它

注意:当一组列表项从第一个参数传递到 lapply 时,这在本地函数内不会成功。 (当从给定 for 循环的列表传递对象时,它也会失败。)如果它是一个,您将能够从结构结果中提取“.Names”属性和处理顺序。正在处理的命名向量。

> lapply( list(a=4,b=5), function(x) {nm <- deparse(substitute(x)); strsplit(nm, '\\[')} )
$a # This "a" and the next one in the print output are put in after processing
$a[[1]]
[1] "X" "" "1L]]" # Notice that there was no "a"


$b
$b[[1]]
[1] "X" "" "2L]]"

> lapply( c(a=4,b=5), function(x) {nm <- deparse(substitute(x)); strsplit(nm, '\\[')} )
$a
$a[[1]] # but it's theoretically possible to extract when its an atomic vector
[1] "structure(c(4, 5), .Names = c(\"a\", \"b\"))" ""
[3] "1L]]"


$b
$b[[1]]
[1] "structure(c(4, 5), .Names = c(\"a\", \"b\"))" ""
[3] "2L]]"

关于r - 在R中,如何在将对象发送到函数后获取对象的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10520772/

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