programing

R에서 객체가 함수로 전송된 후 객체의 이름을 얻는 방법은 무엇입니까?

oldcodes 2023. 6. 18. 16:16
반응형

R에서 객체가 함수로 전송된 후 객체의 이름을 얻는 방법은 무엇입니까?

나는 그 반대의 것을 찾고 있습니다.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-loop.) "를 추출할 수 있습니다.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]]"  
deparse(quote(var))

나의 직관적인 이해는 인용문이 평가에서 변수 표현식을 동결하고 구문 분석 함수의 역인 디파지 함수가 동결된 기호를 문자열로 되돌립니다.


몇 가지 새로운 논평

대체와 인용문의 차이:

f <- function(x) {
  substitute(x)
}   

그리고.

g = function(x){
  quote(x)
}

두 번째는 항상 x를 반환할 것입니다.quotefunction get as argument) 첫 번째 함수가 함수에 전달된 객체를 반환하는 동안 다음을 시도합니다.

f(z~x+y) # return you z~x+y
g(z~x+y) # return you x

인쇄 방법의 경우 동작이 다를 수 있습니다.

print.foo=function(x){ print(deparse(substitute(x))) }
test = list(a=1, b=2)
class(test)="foo"
#this shows "test" as expected
print(test)

#this (just typing 'test' on the R command line)
test
#shows
#"structure(list(a = 1, b = 2), .Names = c(\"a\", \"b\"), class = \"foo\")"

포럼에서 본 다른 의견들은 마지막 행동이 불가피하다는 것을 암시합니다.패키지에 대한 인쇄 방법을 작성하는 경우에는 이 문제가 발생합니다.

Eli Holmes의 답변에 대해 자세히 설명합니다.

  1. myfunc잘 작동합니다.
  2. (그의 20년 8월 15일 논평에서 논의된 바와 같이) 저는 그것을 다른 기능 안에서 부르고 싶어졌습니다.
  3. 실패하다
  4. (외부 함수에서 호출되는 것이 아니라) 직접 코드화된 함수 에서,deparse(substitute()속임수가 잘 통합니다.
  5. 이것은 모두 그의 대답에 함축되어 있지만, 제가 의식하지 못하는 정도를 엿보는 것의 이점을 위해, 저는 그것을 철자로 쓰고 싶었습니다.
an_object <- mtcars
myfunc <- function(x) deparse(substitute(x))

myfunc(an_object)
#> [1] "an_object"

# called within another function 
wrapper <- function(x){
  myfunc(x)
}

wrapper(an_object)
#> [1] "x"

언급URL : https://stackoverflow.com/questions/10520772/in-r-how-to-get-an-objects-name-after-it-is-sent-to-a-function

반응형