R - 我可以并行循环多个变量吗?

时间:2016-10-25 16:10:33

标签: r loops for-loop

假设我有以下数据集...

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中执行此操作?

1 个答案:

答案 0 :(得分:1)

这有效

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))

titles <- c("This is the first plot", 
            "This one the second", 
            "And this is the third")

par(mfrow = c(2, 2))
if(length(titles) == dim(df)[2]){
  for(i in seq(length(titles))){
    barplot(df[,i], main = titles[i])
  }

}