unitedsaga unitedsaga - 1 month ago 6
R Question

Assigning a list to data frame - getting an error: invalid factor level, NA generated

I am creating a list of numbers and characters inside a loop and assigning that list to a data frame. I have defined each variable before hand and I am not using factor (at least I feel that way). Basically, I want to create a data frame with the variables I have mentioned. Here's the code I am trying to work with:

NumToShow = numeric(0)
MatToShow = character()
flag = numeric(0)

datalist = data.frame(NumToShow,MatToShow,flag)

for (i in 1:3){
NumToShow = i
MatToShow = "aaa"
flag = i^2

Row_i = list(NumToShow,MatToShow,flag)
# Combining all the data
datalist[i,] = Row_i
}


I am receiving the error:

In `[<-.factor`(`*tmp*`, iseq, value = "aaa") :
invalid factor level, NA generated


I am not exactly sure why I am getting it. Any help will be appreciated. I apologize if this is something silly. Thank you :)

Answer

Check ?data.frame():

data.frame(..., row.names = NULL, check.rows = FALSE,
           check.names = TRUE, fix.empty.names = TRUE,
           stringsAsFactors = default.stringsAsFactors())

And then type:

default.stringsAsFactors()
# [1] TRUE

You need to explicitly set stringsAsFactors = FALSE in order for data.frame() to not treat characters as factor.

Comments