0

I have dataframe tr which contins around 1700 rows. I am trying to replace Type column values wherever they are NA with string "None".

I do a quick count to check how many NAs I have in my Type column.

na_count = tr[which(is.na(tr$Type)), ]

na_count contains 8 records.

Now I replace all the NAs with "None" using

ifelse(is.na(tr$Type), tr$Type <- 'None', 0)

The above command is replacing all the 1700 rows with None instead of just the 8. I'm not sure why that is happening.

alistaire
  • 42,459
  • 4
  • 77
  • 117
Pirate X
  • 3,023
  • 5
  • 33
  • 60
  • 2
    `tr$Type <- ifelse(is.na(tr$Type), 'None', tr$Type)` or `tr$Type[is.na(tr$Type)] <- 'None'` – alistaire Sep 11 '19 at 05:16
  • 1
    "I'm not sure why that is happening" - it's happening because `tr$Type <- "None"` assigns "None" to every element of `tr$Type` on the first occurrence of an NA value. – neilfws Sep 11 '19 at 05:20
  • @neilfws shouldn't it execute the `tr$Type <- "None"` only and only if the `if` condition is true and not every element? – Pirate X Sep 11 '19 at 05:22
  • @alistaire can you post it as answer? It worked. Thanks ! – Pirate X Sep 11 '19 at 05:25
  • 1
    Sorry, I've got a personal policy that I only write answers if there's a full [reprex](https://reprex.tidyverse.org/articles/reprex-dos-and-donts.html) in the question – alistaire Sep 11 '19 at 05:29

0 Answers0