簡體   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