【问题标题】:R - Can I loop over multiple variables in parallel?R - 我可以并行循环多个变量吗?
【发布时间】: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)){,然后使用索引对“标题”进行子集化

标签: r loops for-loop


【解决方案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])
  }

}

【讨论】:

  • 谢谢!这确实有效。现在我只需要弄清楚如何以及为什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多