简体   繁体   English

使用for语句比较R中数据框中的图

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

I am trying to compare and plot a variable's distribution with that of the variable's log transformation. 我正在尝试比较变量的分布和变量的对数转换的分布。

What I am saying below, for every variable in mtcars if it is either a numeric or an integer return a histogram of it, then return a histogram with a log transformation, so that I can compare. 我在下面说的是,对于mtcars中的每个变量,如果它是数字或整数,则返回它的直方图,然后通过对数转换返回直方图,以便进行比较。

Any help would be appreciated. 任何帮助,将不胜感激。

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

This has nothing to do with hist() , it's the if statement that does not make much sense. 这与hist()无关,这是if语句,没有多大意义。

  • You want to use is.numeric() and is.integer() 您要使用is.numeric()is.integer()
  • Both require the argument is.numeric(mtcars[,i]) and is.integer(mtcars[,i]) . 两者都需要参数is.numeric(mtcars[,i])is.integer(mtcars[,i])
  • is.numeric() and is.integer() already return a boolean , so there is no need to check == T is.numeric()is.integer()已经返回boolean ,因此无需检查== T

Your code should read: 您的代码应为:

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

You should also know that it's almost always better to leverage the apply functions family instead of loops, eg: 您还应该知道,利用apply函数系列而不是循环通常总是更好,例如:

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

You should use function is.numeric and is.integer . 您应该使用函数is.numericis.integer Using as. 使用as. makes no sense in an if statement. if语句中没有任何意义。

This would be the correct approach: 这将是正确的方法:

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