2012-03-12 88 views
9

我想知道是否有人可以幫助我在函數中使用變量名稱。 我已經放在一起,對變量進行排序然後產生一個位圖的點圖,但我不能讓R將變量名稱傳遞給plot標題。傳遞變量名稱來繪製函數標題

實施例數據

id<-c(1,2,3) 
blood<-c(1,2,10) 
weight<-c(1,2,13) 


mydata<-as.data.frame(cbind(id,blood,weight)) 
mydata$blood 

#######SORTED DOT PLOT#### 


Dplotter<-function (id,x,Title=""){ 
if (is.null(Title)) {Title=""} else {Title=Title} 

DIR<-paste("C:/temp/WholePlots/New/",Title,".bmp",sep="") 

D<-as.data.frame(cbind(id,x)) 
x1<-as.data.frame(D[order(x),]) 

bmp(DIR) 
dotchart(x1$x,labels=id,main=Title,pch=16) 
dev.off() 
} 


############### 
Dplotter(mydata$id,mydata$blood,"Blood") 

Dplotter(mydata$id,mydata$weight,"Weight") 
  1. 在功能的第二行,我想通過在可變 名,像

    `if (is.null(Title)) {Title=varname(x)} else {Title=Title}` 
    

    使得我不t必須在功能標題字段 (例如Dplotter(mydata $ id,mydata $ blood)

    基本上,如何在函數中粘貼變量名?如果可以從 標題中取出數據集名稱(沒有附加數據集,我已經告訴其實的做法不好),那麼 會更好,因此您可以取而代之以獲得mydata$blood,這樣就可以得到 「鮮血」在標題中。

    我找不到一個簡單的解決方法,在 函數中粘貼變量名。如您所知,將變量名稱放入一個 paste()函數將返回變量的值(以便 繪圖標題填充值而不是變量名稱)。

  2. 我還想更進一步自動化功能,這樣我可以 只是把數據集和ID,然後有功能重複 在數據集中的每個變量。顯然這需要先解決 問題1,否則標題和文件名都會遇到 問題。

回答

13

一般的答案是deparse(substitute(x))。例如。

fooPlot <- function(x, main, ...) { 
    if(missing(main)) 
     main <- deparse(substitute(x)) 
    plot(x, main = main, ...) 
} 

這是在使用中:

set.seed(42) 
dat <- data.frame(x = rnorm(1:10), y = rnorm(1:10)) 
fooPlot(dat, col = "red") 

主要生產:

using <code>deparse(substitute())</code> to title a plot

在你的具體的例子,雖然,這不會工作,因爲你不想做dat$x作爲標題,你只需要x。我們可以做多一點操控但是:

fooPlot <- function(x, main, ...) { 
    if(missing(main)) { 
     main <- deparse(substitute(x)) 
     if(grepl("\\$", main)) { 
      main <- strsplit(main, "\\$")[[1]][2] 
     } 
    } 
    plot(x, main = main, ...) 
} 

這爲fooPlot(dat$x, col = "red")給出:

second attempt

注意此代碼做了一些假設,即main不是一個載體,將有永遠只能是一個$在傳遞給plot的對象中(也就是說,例如上面的代碼不能使用嵌套列表)。

+0

非常感謝。它工作得很好。 有沒有人對如何做2有任何建議(問題2,見上文)。例如,讓foo繪圖在另一個函數「PlotALL」中運行,該函數將數據集的所有變量逐一傳遞給foo plot? 這將允許我寫 ## PlotAll(id,mydata) 並獲得所有打印的圖形。 非常感謝 – 2012-03-12 12:29:20

1

您需要檢索一組字符串和變量名稱,並將它們用於繪圖和文件名的標題。

我將使用longley數據集來說明這個技巧。

data(longley, package="datasets") 

#return a vector with variable names 
colnames(longley) 
names(longley) #equivalent 

#get the name of a specific variable (column number): 
names(longley)[1] 

要繪製每個變量,得到兩組字符串:變量名和文件名:

var.names=names(longley) 
file.names=paste(var.names, "bmp", sep=".") 
#with an extra step to prefix a directory to those filenames 

for (i in 1:ncol(longley)) { 

    bmp(file=file.names[i]) 
    plot(longley[[i]], main=var.names[i], ylab="") 
    dev.off() 
} 

ylab = 「」,否則它給出了一個愚蠢的 「朗利[我]」 作爲y標籤,如果我使用var.name [i]作爲ylab,它將是多餘的。

+0

親愛的p_barill,這正是我需要的。非常感謝你的幫助。 – 2012-03-13 14:54:20