0

我正在尝试运行一个 for 循环,该循环生成以列名作为 x 标签的图。这应该是直截了当的,但是 R 在解析列名时遇到了问题,因为它们中有括号和空格,我想将它们保留在情节中,因为它们是描述性的作者姓名。

这是列的名称。

colnames(shorty_ks)[colnames(shorty_ks)=="K.mean.hr"] <- "BASEmetab"
colnames(shorty_ks)[colnames(shorty_ks)=="kn2o.Churchill"] <- "Churchill et al. (1962)"
colnames(shorty_ks)[colnames(shorty_ks)=="kn2o.Owens"] <- "Owens (1964)"
colnames(shorty_ks)[colnames(shorty_ks)=="kn2o.Oconnor"] <- "OConnor and Dobbins (1958)"

这是 for 循环(当我使用不包括空格和括号的简单文本时有效):

colNames <- names(shorty_ks)[2:4]
BASEmetab <- shorty_ks$BASEmetab


for(i in colNames){
  plt <- ggplot(shorty_ks, aes_string(x=i, y = BASEmetab)) + xlab(bquote(. (i)~k~(h^-1)))+ ylab(expression(BASEmetab~k~(h^-1)))+
theme_gray()+
geom_smooth(method="lm",se=FALSE) + geom_point() +
scale_color_brewer(palette="Dark2")
print(plt)
Sys.sleep(2)
}

但是当我使用括号和空格运行代码时,我收到以下错误消息:

Error in parse(text = x) : <text>:1:11: unexpected symbol
1: Churchill et
              ^

可重现的数据:

dput(head(shorty_ks))
structure(list(BASEmetab = c(0.11409531425, 0.0716102175833333, 
0.09953587425, 0.248902252416667, 0.114263822125, 0.1530849725
), `Churchill et al. (1962)` = c(0.0354781748244595, 0.0511254328535874, 
0.0351401193406382, 0.0432339955562482, 0.0498228392372491, 
0.0342448057447306
), `OConnor and Dobbins (1958)` = c(0.0336761898724322, 0.0447691111499001, 
0.0333255117582665, 0.0359191513743014, 0.043530785730249, 0.0324037193153706
), `Owens (1964)` = c(0.0585830015888074, 0.10004459351892, 
0.0583011578948275, 
0.102948639254916, 0.0987018589393615, 0.0575186770232462)), .Names = 
c("BASEmetab", 
"Churchill et al. (1962)", "OConnor and Dobbins (1958)", "Owens (1964)"
), row.names = c(NA, 6L), class = "data.frame")
4

1 回答 1

0

您不应该在列名中有空格。列名必须是有效的变量名,所有列美学映射才能工作。最好不要更改列名,只需有一个单独的标签向量即可​​使用。

这是原始名称的数据

shorty_ks <- structure(list(BASEmetab = c(0.11409531425, 0.0716102175833333, 
0.09953587425, 0.248902252416667, 0.114263822125, 0.1530849725
), kn2o.Churchill = c(0.0354781748244595, 0.0511254328535874, 
0.0351401193406382, 0.0432339955562482, 0.0498228392372491, 0.0342448057447306
), kn2o.Oconnor = c(0.0336761898724322, 0.0447691111499001, 0.0333255117582665, 
0.0359191513743014, 0.043530785730249, 0.0324037193153706), kn2o.Owens = c(0.0585830015888074, 
0.10004459351892, 0.0583011578948275, 0.102948639254916, 0.0987018589393615, 
0.0575186770232462)), .Names = c("BASEmetab", "kn2o.Churchill", 
"kn2o.Oconnor", "kn2o.Owens"), row.names = c(NA, 6L), class = "data.frame")

然后只需创建一个“漂亮”名称的向量

col_labels <- c(
  kn2o.Churchill="Churchill et al. (1962)", 
  kn2o.Oconnor="OConnor and Dobbins (1958)", 
  kn2o.Owens="Owens (1964)")

然后你可以将它用于循环中的标签

colNames <- names(shorty_ks)[2:4]
for(i in colNames){
  plt <- ggplot(shorty_ks, aes_string(x=i, y = "BASEmetab")) + 
    xlab(bquote(. (col_labels[i])~k~(h^-1)))+ 
    ylab(expression(BASEmetab~k~(h^-1)))+
    theme_gray()+
    geom_smooth(method="lm",se=FALSE) + geom_point() +
    scale_color_brewer(palette="Dark2")
  print(plt)
}
于 2018-07-14T00:14:47.813 回答