簡體   English   中英

使用for語句比較R中數據框中的圖

[英]Using for statement to compare plots in a dataframe in R

我正在嘗試比較變量的分布和變量的對數轉換的分布。

我在下面說的是,對於mtcars中的每個變量,如果它是數字或整數,則返回它的直方圖,然后通過對數轉換返回直方圖,以便進行比較。

任何幫助,將不勝感激。

for(i in ncol(mtcars)){
   par(mfcol = c(1,2))
   if (as.numeric | as.integer(mtcars[,i]) == T){
      return(hist(mtcars[,i]))}
   if (as.numeric | as.integer(mtcars[,i]) == T){
      return(hist(log(mtcars[,i])+1))}
}

Error in as.numeric | as.integer(mtcars[, i]) == T : 
operations are possible only for numeric, logical or complex types

這與hist()無關,這是if語句,沒有多大意義。

  • 您要使用is.numeric()is.integer()
  • 兩者都需要參數is.numeric(mtcars[,i])is.integer(mtcars[,i])
  • is.numeric()is.integer()已經返回boolean ,因此無需檢查== T

您的代碼應為:

for(i in ncol(mtcars)){
  if (is.numeric(mtcars[,i]) | is.integer(mtcars[,i])){
    return(hist(mtcars[,i]))
    return(hist(log(mtcars[,i])+1)}
}

您還應該知道,利用apply函數系列而不是循環通常總是更好,例如:

apply(mtcars, 2, function(x) {hist(log(x)+1); hist(x)})

您應該使用函數is.numericis.integer 使用as. if語句中沒有任何意義。

這將是正確的方法:

for(i in ncol(mtcars)){
    par(mfcol = c(1,2))
    if (is.numeric(mtcars[,i] | is.integer(mtcars[,i])){
       return(hist(mtcars[,i]))
    }
    else {
       return(hist(log(mtcars[,i])+1))
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM