R绘制基于提供的索引值选择列的值

时间:2019-01-21 20:03:53

标签: r ggplot2 plot

我正在尝试找出如何以一种特殊的方式绘制一些值。说我有以下示例数据:

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或其他格式)作图还很陌生,因此非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这不是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")