Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid factor level, NA generated when pasting in a dataframe in r

Tags:

r

I cannot paste the correct data into the dataframe using rbind. Here is the problem

Results <- dataframe()

Value will store the hospital name that meets the selection criteria and y[1,2] is the name of the State

Here is what I get when I try to past the results into the blank dataframe results.

class(results)
[1] "data.frame"
value
[1] "JOHN C LINCOLN DEER VALLEY HOSPITAL"
y[1,2]
[1] "AZ"
class(value)
[1] "character"
class(y[1,2])
[1] "character"
results <- rbind(results,as.list(c(value,y[1,2])))
Warning messages:
1: In `[<-.factor`(`*tmp*`, ri, value = "JOHN C LINCOLN DEER VALLEY HOSPITAL") :
  invalid factor level, NA generated
2: In `[<-.factor`(`*tmp*`, ri, value = "AZ") :
  invalid factor level, NA generated
results
  X.ARKANSAS.METHODIST.MEDICAL.CENTER. X.AR.
1    ARKANSAS METHODIST MEDICAL CENTER    AR
2                                 <NA>  <NA>
3                                 <NA>  <NA>

How to solve this? Many thanks

like image 496
user3782429 Avatar asked Dec 25 '22 07:12

user3782429


1 Answers

You have a factor when you want a character. Do an str() on your data frame to identify the columns that are factors then suppose your data.frame is called Mydf and the factor columns are columns 3 and 5

Mydf[,c(3,5)] <- sapply(Mydf[,c(3,5)],as.character) 
like image 90
JeremyS Avatar answered May 24 '23 07:05

JeremyS