繁体   English   中英

遍历变量向量

[英]Loop through vector of variables

我有一个过程,想一次遍历一个变量。

尽管我的过程要复杂得多,但是我使用以下内容来说明基本问题。

假设我想建立一个直方图并对iris每个变量做很多其他事情。 以下实现了该目标:

hist(iris$Sepal.Length, main = paste("Histogram of Sepal.Length"))
hist(iris$Sepal.Width, main = paste("Histogram of Sepal.Width"))
hist(iris$Petal.Length, main = paste("Histogram of Petal.Length"))
hist(iris$Petal.Width, main = paste("Histogram of Petal.Width"))

但是,我的数据框更大,过程也更复杂。 我想将其包装在如下所示的循环中(这不起作用,但这是我在脑海中设想的方式)。

name.list <- names(iris)

for (i in 1:4) {

  print(i)
  print(name.list[i])
  print(paste0('iris$', name.list[i]))

  hist(paste0('iris$', name.list[i]), main = paste("Histogram of ", name.list[i]))

  # A bunch of other stuff I need to do with this variable
  # ...
  # ...

}

我在这里想念什么? 如何包装此代码一次遍历一个?

如果将data.frame视为列表会更容易。 data.frame类的对象是一个列表,因此您可以使用列表选择[[这里:

for( i in names(iris)){
  tmp <- iris[[i]]
  if(is.numeric(tmp))
    hist(tmp, main = paste("Histogram of",i))
}

另请参见以下问题的答案: 将data.frame列名传递给函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM