2013-04-20 7 views
1

입력을 기반으로 데이터 프레임의 출력에 동적 이름을 지정하려고합니다.입력을 기반으로 동적으로 열 이름 변경

get.max2(mtcars, mpg) 

     name mpg 
Volvo 142E 33.9 

내가 대답은 경기를 함께 할 수있는 뭔가가 생각 : 나는 다음과 같이 할,

get.max2(mtcars, mpg) 

     name title 
Volvo 142E 33.9 

을하지만 :

get.max2 <- function(data = NULL, column) 
{ 
    #require(qdap) 
    col <- eval(substitute(column), data) 
    max <- max(eval(substitute(column), data)) 
    name <- lookup(col, max, rownames(data)) 
    name <- name[!is.na(name)] 
    #title <- do.call('paste', list(paste(match.call()[1]))) 
    df <- data.frame(name = name, title = max(col)) 
    print(df) 
} 

현재 출력은 다음과 같습니다. call/do.call을 사용하지만,이 기능을 사용할 때는 내 지식이 모호합니다. 가능하다면 누구나 알 수 있습니까?

도움 주셔서 감사합니다.

답변

1

당신은 title=..입니다.

는 대신 사용할 : 당신이 한 것과

title = paste(match.call()[-(1:2)], collapse=" ") 
# the collapse argument is optional, it's not clear 
# how you would like to handle multiple arguments 

주의 사항 두 가지 주요 차이점 :

  1. [1] 대신 [-(1:2)]를 사용하여. match.call()의 요소는 원하지 않는 함수 이름입니다. 또는 두 번째 인수 만 원하면 match.call()[3]을 사용할 수 있습니다.
  2. 이 경우 do.call(.)이 필요하지 않습니다. paste은 정상적으로 작동합니다.
0

?deparse?substitute과 같은 것을 찾고 있습니다.

variableName <- function(x) { 
    return(deparse(substitute(x))) 
} 

variableName(title) 
# [1] "title" 

variableName(mpg) 
# [1] "mpg" 
0

모두의 도움에 감사드립니다! 내가 발견 한 또 다른 해결 방법은 처리 후 데이터 프레임의 이름을 바꾸는 것이 었습니다.

get.max2 <- function(data = NULL, column) 
{ 
    #require(qdap) 
    #require(gdata) 
    col <- eval(substitute(column), data) 
    max <- max(eval(substitute(column), data)) 
    name <- lookup(col, max, rownames(data)) 
    name <- name[!is.na(name)] 
    df <- data.frame(name = name, title = max(col)) 
    title2 <- do.call('paste', list(paste(match.call()[3]))) 
    df <- rename.vars(df, 'title', title2, info = F) 
    return(df) 
} 

반환 :

get.max2(mtcars, mpg) 

     name mpg 
Volvo 142E 33.9 
관련 문제