R 绘图值,用于根据提供的索引值选择列



我试图弄清楚如何以一种特殊的方式绘制一些值。假设我有以下示例数据:

set.seed(100)
test.df <- as.data.frame(matrix(1:36,nrow=6))
test.df$V7 <- sample(1:6,6)
test.df$V8 <- seq(1:6)
colnames(test.df) <- c("col1","col2","col3","col4","col5","col6","index","id")
test.df
    col1 col2 col3 col4 col5 col6 index id
1    1    7   13   19   25   31     2  1
2    2    8   14   20   26   32     6  2
3    3    9   15   21   27   33     3  3
4    4   10   16   22   28   34     1  4
5    5   11   17   23   29   35     4  5
6    6   12   18   24   30   36     5  6

我想通过使用"索引"列作为选择要选择的列 (1-6) 的方法,绘制前 6 列的值。这将是 y 轴。x 轴将为"id"。本质上,第一个 y 值将为 7,因为索引为第一个值选择列 2。第二个 y 值为 32,因为索引值指示第 6 列。

如果我能澄清其他任何事情,请告诉我。我对在 R(ggplot2 或其他)中绘图相当陌生,因此非常感谢任何帮助。

这不是 ggplot2 的问题。

首先,您可以创建一个列"y":

test.df[, "y"] <- 0
for (i in (1:nrow(test.df))) {
test.df[i, "y"] <- test.df[i, paste0("col", test.df[i, "index"])]
    }

然后你可以用plot进行绘图:

plot(y ~ id, data = test.df, type = "l")

最新更新