为什么我在函数内外得到不同的行为?

时间:2017-03-29 17:44:48

标签: r

在函数中执行此代码时,我得到不同的结果。我错过了什么?

有效的代码:

adf$GarageCond = as.character(adf$GarageCond)
adf[is.na(adf$GarageCond), "GarageCond"] = "None"
adf$GarageCond = as.factor(adf$GarageCond)    
adf$GarageCond = ordered(adf$GarageCond, levels=c("None","Po","Fa","TA","Gd","Ex"))

功能:

cnvtNaAndOrder = function(df, colname)
{
  #
  # Change NA's to a "None" factor 
  #
  df[,eval(quote(colname))] = as.character(df[,eval(quote(colname))])
  adf[is.na(df[,eval(quote(colname))]), eval(quote(colname))] = "None"
  df[,eval(quote(colname))] = as.factor(df[,eval(quote(colname))])
  df[,eval(quote(colname))] = ordered(df[,eval(quote(colname))], levels=c("None","Po","Fa","TA","Gd","Ex"))

  return(df)
}

直接执行代码按预期工作:

adf$GarageCond = as.character(adf$GarageCond)
adf[is.na(adf$GarageCond), "GarageCond"] = "None"
adf$GarageCond = as.factor(adf$GarageCond) 
adf$GarageCond = ordered(adf$GarageCond, levels=c("None","Po","Fa","TA","Gd","Ex"))

summary(adf$GarageCond)
None   Po   Fa   TA   Gd   Ex 
  81    7   35 1326    9    2 

str(adf$GarageCond)
 Ord.factor w/ 6 levels "None"<"Po"<"Fa"<..: 4 4 4 4 4 4 4 4 4 4 ...

通过该函数执行我认为是等效代码的内容会产生警告并产生不同的结果:

adf = cnvtNaAndOrder(adf, "GarageCond")
Warning message:
In `[<-.factor`(`*tmp*`, iseq, value = c("None", "None", "None",  :
  invalid factor level, NA generated

summary(adf$GarageCond)
None   Po   Fa   TA   Gd   Ex NA's 
   0    7   35 1326    9    2   81 

str(adf$GarageCond)
 Ord.factor w/ 6 levels "None"<"Po"<"Fa"<..: 4 4 4 4 4 4 4 4 4 4 ...

似乎as.factor()正在发出警告而不是转换&#34;无&#34;一个因素。请注意,我还尝试使用df[,"GarageCond"]表单来直接执行代码中的列,并且它可以正常工作。

我错过了什么?为什么会有不同的行为?

1 个答案:

答案 0 :(得分:0)

这是一个我看不到的简单拼写错误。