1

My question is a combination of this and this question.

I have a data frame:

df <- data.frame("ID" = c(1,2,3,4),
                 "char" = c("a","b","c","d"))

and I want to change a single value, like

df[1,1] <- 10

which is working. When I try this

df[2,2] <- "f"

or

df$char[1] <- "f"

or

df$char[1] <- as.character("f")

I get the following warning:

"Warning message:
In `[<-.factor`(`*tmp*`, 2, value = c(1L, NA, 3L, 4L)) :
  invalid factor level, NA generated"

How do I change the content in the column "char"?

camille
  • 16,432
  • 18
  • 38
  • 60
DerDressing
  • 315
  • 1
  • 4
  • 19
  • 1
    easiest approach would be to do `df <- data.frame(ID = c(1,2,3,4), char = c("a","b","c","d"), stringsAsFactors = FALSE)` and then everything would work. – Ronak Shah Aug 20 '19 at 13:41
  • @RonakShah that works if they have access to creating the data frame like this, but that could easily not be their real life situation – camille Aug 20 '19 at 14:50
  • @camille You are right. I'm looking for a simple solution for data frames, which are already created.. – DerDressing Aug 23 '19 at 06:44

1 Answers1

1

We can include levels beforehand and then do the assignment

df$char <- factor(df$char, levels = c(levels(df$char), "f"))
df[2,2] <- "f"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you, this is working. But I'm still wondering, why this allegedly simple assignment requires two lines of rather tricky code.. – DerDressing Aug 23 '19 at 06:48
  • @DerDressing Because `factor` columns need that level before the assignment – akrun Aug 23 '19 at 13:36