태그 보관물: r

r

R에서 객체로 함수에 보낸 후 객체의 이름을 얻는 방법은 무엇입니까? mean.x <- mean(a$x)

의 반대를 찾고 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
$a[[1]]
[1] "X"    ""     "1L]]"


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

> lapply( c(a=4,b=5), function(x) {nm <- deparse(substitute(x)); strsplit(nm, '\\[')} )
$a
$a[[1]]
[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))

내 직관적 인 이해 따옴표가 평가에서 var 또는 표현식을 고정하고 구문 분석 함수의 역인 deparse 함수는 동결 된 기호를 다시 문자열로 만듭니다.


답변

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

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 shows 
#"structure(list(a = 1, b = 2), .Names = c(\"a\", \"b\"), class = \"foo\")"
test

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


답변