我正在尝试运行一个 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")