2012-10-11 164 views
1

我想組裝一個直方圖的標題在R我想要從兩個來源,第一個矢量(death.cause)指定呃致死原因,第二個來自data.frame的字段,我使用list,deathratecols進行索引,以獲取該字段。main =粘貼(替代(...),替代(...))在R_hist_title

> death.cause 

> [[1]] [1] "Heart Attack" 
> 
> [[2]] [1] "Heart Failure" 
> 
> [[3]] [1] "Pneumonia" 


> deathratecols 

> [1] 11 17 23 

我想組裝如下標題:Heart Attack(x-bar = 7.63763),其中x-bar是數據列的平均值。我可以將這兩部分分開工作,如下所示。

> main=substitute(x, list(x=death.cause[[i]]))) # gives title "Heart Attack" 

> main=substitute(bar(X)==k, list(k=mean(outcome[, deathratecols[i] ], na.rm=TRUE ))) # gives title x-bar=7.63763 

但我的努力,把這兩個使用粘貼()都失敗了。

?有人指出我的方式錯誤請

回答

2

提前格式化標題sprintf聲明並將其傳遞到main。簡單的例子:

a <- "foo" 
b <- "bar" 
title <- sprintf("This combines %s and %s", a, b) 
hist(rnorm(10), main = title) 

也許是這樣的(但可能無法正常工作,因爲你沒有提供一個例子一起工作):

title <- sprintf("%s, (x-bar = %s)", death.cause[[i]], mean(outcome[, deathratecols[i]]) 
+0

注意:如果需要,請使用'%f'來格式化數字。 – Maiasaura

+0

感謝您的回答,這給了我一個瞭解R的另一部分的刺激。我無法按需要使sprintf()工作。但是對於記錄,我發現可以使用substitute()組裝一個字符串,就像paste()一樣,儘管不需要逗號之間的逗號,所以'code main = substitute(cod(bar(x)= y = round(mean(outcome [,deathratecols [i]],na.rm = TRUE),2)' – bobox

+0

...給了我標題我想即CauseOfDeath(xbar = RateColumnMean)再次感謝您的建議 – bobox

0

您可以將替代()和粘貼()之類如下:

hist(outcome[, deathratecols[i]], 
    main=substitute(paste(death.cause[[i]], "(", bar(X), "=", k, ")"), list(k=mean(outcome[, deathratecols[i]], na.rm=TRUE)))) 

它爲我工作。