【发布时间】:2016-10-26 14:54:52
【问题描述】:
假设我有以下数据集...
df <- data.frame(first = sample(seq(0, 100, 1), 10),
second = sample(seq(0, 1, 0.01), 10),
third = sample(seq(0, 1000, 1), 10))
...以及包含df中每个变量的标题的以下向量。
titles <- c("This is the first plot",
"This one the second",
"And this is the third")
现在我想为每个变量创建一个条形图。以下是我手动操作的方法:
par(mfrow = c(2, 2))
barplot(df[, 'first'], main = titles[1])
barplot(df[, 'second'], main = titles[2])
barplot(df[, 'third'], main = titles[3])
但我希望能够使用 for 循环来做到这一点。下面是一个伪循环示例,描述了我希望如何做到这一点。
par(mfrow = c(2, 2))
for(x in names(df), y in titles) {
barplot(df[, x], main = y)
}
有没有办法在 R 中做到这一点?
【问题讨论】:
-
您可以使用
for(i in seq_along(df)){,然后使用索引对“标题”进行子集化