Dambo
Dambo

Reputation: 3496

How to fix a 'malformed factor'?

I'm not sure at which point it happened, but I ended up with a vector like this:

vec <- structure(c(1L,2L, 33L), .Label = c("first", "second"), class = "factor")

And when I call vec I get:

Error in as.character.factor(x) : malformed factor

I would like to "rescue" this vector, for example by substituting NA to 33L, but cannot even do something like as.character(vec). How do I fix it?

Upvotes: 3

Views: 9276

Answers (1)

Roland
Roland

Reputation: 132706

vec <- structure(c(1L,2L, 33L), .Label = c("first", "second"), class = "factor")

levels(vec) <- levels(vec)

print(vec)
#[1] first  second <NA>  
#Levels: first second

You should investigate why you have a malformed factor and fix that.

Upvotes: 2

Related Questions