如何在字符串中使用列名?

时间:2018-07-25 13:22:03

标签: r ggplot2

我有一组数据(称为currentdata),其格式如下:

season_year   station   depth     Pb
autumn 2016      1        -1     0.5
autumn 2016      1         1     0.6
autumn 2016      1         3     0.7
autumn 2016      2        -1     0.1
autumn 2016      2         1     0.4
autumn 2016      2         3     0.2
autumn 2016      3        -1     0.6
autumn 2016      3         1     0.4
autumn 2016      3         3     0.7
summer 2017      1        -1     0.1
summer 2017      1         1     0.3
summer 2017      1         3     0.4

我一直在尝试使用以下代码将其转换为ggplot:

plot <- ggplot(currentdata, aes(x=depth, y= currentdata[[4]])) + 
  geom_bar(stat = "identity") +
  scale_x_reverse() +
  coord_flip()  +
  labs(title = paste("Pb", "pore water concentrations"), x = "depth (cm)", y = "concentration (ug/l)") +   #CHANGE
  facet_grid(season_year~station)
plot

我尝试在没有coord_flip的情况下执行此操作,但是这会返回一个空图,因此我陷入了奇怪的“将变量放在错误的轴上并翻转它们”的问题。无论如何,这在这里并不重要。

我的问题是,我是从具有多个金属轮廓的较大表格中创建该表格的,因此我将不得不分别为每种金属制作一张图表,因此每次为一种新金属进行此操作时,必须将我想要的金属名称更改为标签。取而代之的是,我想编写一个看起来更像这样的代码。

    plot <- ggplot(currentdata, aes(x=depth, y= currentdata[[4]])) + 
      geom_bar(stat = "identity") +
      scale_x_reverse() +
      coord_flip()  +
      labs(title = paste([name of the 4th column in the data.frame], "pore water concentrations"),
        x = "depth (cm)",
        y = paste([name of the 4th column in the data.frame], "concentration (ug/l)")) +
      facet_grid(season_year~station)
    plot

这将防止我犯愚蠢的错误,因为我忘记在一个地方更改金属名称,而在另一个地方却没有更改金属名称,从而制作了误贴图。

对于我尝试过的标签

paste(currentdata$cols[4], "pore water concentrations"),
paste(currentdata.columns(4), "pore water concentrations"),
paste(colnames(currentdata[,4]), "pore water concentrations"),
paste(colnames(currentdata, [4]), "pore water concentrations"),

他们都不起作用,所以我可能会以某种方式考虑这个错误。

对不起,如果我犯了一些新手错误,我对使用R和stackoverflow都是新手。我正在使用RStudio编写代码。

编辑:哈!我考虑了一个字符串的概念,并提出了这个建议:

column_names <- colnames(currentdata)

plot <- ggplot(currentdata, aes(x=depth, y=currentdata[[4]])) +
  geom_bar(stat = "identity") +
  scale_x_reverse() +
  coord_flip()  +
  labs(title = paste(column_names[4], "pore water concentrations"),
    x = "depth (cm)",
    y = paste(column_names[4], "concentration (ug/l)")) +
  facet_grid(season_year~station)
plot

因此,这实际上只是一个非常简单的答案。我将其保留在这里,以防其他人发现它的某些用途。感谢LAP让我从另一个角度考虑这个问题!

0 个答案:

没有答案
相关问题