-1

I'm new to R and I'm using a data set from kaggle on bombing operations in WWII

I wanted to replace all the NA's in a column with "UKNOWN" but I get this

Warning message:
In `[<-.factor`(`*tmp*`, is.na(operations[,"theater.of.operations"]),  :
invalid factor level, NA generated

This is how I tried to do it

operations[, "theater.of.operations"][is.na(operations[, "theater.of.operations"])] <- "UNKNOWN"

How else should I try to do this?

Sotos
  • 51,121
  • 6
  • 32
  • 66
Niall
  • 518
  • 1
  • 6
  • 23
  • 2
    convert to character – Sotos Mar 31 '17 at 14:50
  • 1
    Try using as.character() to cast your df column to a character first as Sotos mentions – Single Entity Mar 31 '17 at 14:55
  • Thanks I didn't really know what was meant by "convert to character" but @SingleEntity made it more clear, so I used "operations$theater.of.operations <- as.character(operations$theater.of.operations) " and it worked. – Niall Mar 31 '17 at 15:03
  • 1
    Possible duplicate of [invalid factor level, NA generated](http://stackoverflow.com/questions/16819956/invalid-factor-level-na-generated) – Ronak Shah Mar 31 '17 at 15:06
  • The Solution to that question is different to mine – Niall Mar 31 '17 at 15:08
  • 1
    Glad it worked for you, I shall add an answer to your question to make it official :) – Single Entity Mar 31 '17 at 15:10
  • Another possible dupe: [replace in a factor column in R](http://stackoverflow.com/questions/39126537/replace-na-in-a-factor-column-in-r). – lmo Mar 31 '17 at 15:11
  • 1
    Yes these are close duplicates, but not exact. I feel there has to be some understanding that the user may not have enough present knowledge to understand how those questions relate to their question, and that should be acceptable. – Single Entity Mar 31 '17 at 15:14

1 Answers1

2

To convert NA (which is not of string type) to a string such as "UNKNOWN" you need to cast your dataframe column to a string as follows.

operations$theater.of.operations <- as.character(operations$theater.of.operations)

The critical element being the function as.character() which casts to your required character variable type.

Single Entity
  • 2,925
  • 3
  • 37
  • 66