无效因子水平与循环

时间:2023-01-22 22:56:37

Please, I can't fix next problem:

求你了,我不能解决下一个问题:

 str(state_table)

chr [1:54] "AK" "AL" "AR" "AZ" "CA" "CO" "CT" "DC" "DE" "FL" ...

 z <- data.frame(stringsAsFactors=FALSE)

 for (i in state_table){z <- rbind(z, c(i))}

This code returns:

这段代码的回报:

 invalid factor level, NA generated

 In `[<-.factor`(`*tmp*`, ri, value = "AL") :

1 个解决方案

#1


3  

> rbind(z, "AL")
  X.AL.
1    AL
> str(z)
'data.frame':   0 obs. of  0 variables
> str(rbind(z, "AL"))
'data.frame':   1 obs. of  1 variable:
 $ X.AL.: Factor w/ 1 level "AL": 1

So afer the first item is added, the first columns is a factor with one level and you won't be able to rbind any more since the input will not be in the set of levels. It should work if you set stringsAsFactors to FALSE in options (or if you set up the datafreame with more care as ahaving a character column rather than using the defaults.

因此,在添加第一个项目之后,第一个列是具有一个级别的因子,您将无法再进行rbind操作,因为输入将不在级别集中。如果在选项中将stringsAsFactors设置为FALSE(或者更小心地设置datafreame,使之具有字符列,而不是使用缺省值),那么它应该可以工作。

> options(stringsAsFactors=FALSE)
> z <- data.frame()
> str(rbind(z, "AL"))
'data.frame':   1 obs. of  1 variable:
 $ X.AL.: chr "AL"

> for (i in state.abb){z <- rbind(z, c(i))}
> str(z)
'data.frame':   50 obs. of  1 variable:
 $ X.AL.: chr  "AL" "AK" "AZ" "AR" ...

#1


3  

> rbind(z, "AL")
  X.AL.
1    AL
> str(z)
'data.frame':   0 obs. of  0 variables
> str(rbind(z, "AL"))
'data.frame':   1 obs. of  1 variable:
 $ X.AL.: Factor w/ 1 level "AL": 1

So afer the first item is added, the first columns is a factor with one level and you won't be able to rbind any more since the input will not be in the set of levels. It should work if you set stringsAsFactors to FALSE in options (or if you set up the datafreame with more care as ahaving a character column rather than using the defaults.

因此,在添加第一个项目之后,第一个列是具有一个级别的因子,您将无法再进行rbind操作,因为输入将不在级别集中。如果在选项中将stringsAsFactors设置为FALSE(或者更小心地设置datafreame,使之具有字符列,而不是使用缺省值),那么它应该可以工作。

> options(stringsAsFactors=FALSE)
> z <- data.frame()
> str(rbind(z, "AL"))
'data.frame':   1 obs. of  1 variable:
 $ X.AL.: chr "AL"

> for (i in state.abb){z <- rbind(z, c(i))}
> str(z)
'data.frame':   50 obs. of  1 variable:
 $ X.AL.: chr  "AL" "AK" "AZ" "AR" ...