Benjamin
Benjamin

Reputation: 11860

Insert character value in specific row/column of a pre-assigned data frame

I have a pre-assigned data frame to hold some output data:

d  = data.frame(a=character(5), b=numeric(5))

I am trying to assign values to specific rows of d$a:

d$a[3] = "foo"

Which works fine for the numeric fields, but inserts NA rather than the value because it is expecting a factor:

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

How can I insert the correct value?

Upvotes: 0

Views: 5768

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

This is a classic case of where you may want to remember to use stringsAsFactors = FALSE when creating your data.frame.

Alternatively, you can manually add the missing level before trying to make the replacement. (For example, levels(d$a) <- c(levels(d$a), "foo")).

Try the following examples:

d <- data.frame(a=character(5), b=numeric(5), stringsAsFactors = FALSE)
d$a[3] <- "foo"

e <- data.frame(a=character(5), b=numeric(5))
levels(e$a) <- c(levels(e$a), "foo")
e$a[3] <- "foo"

Upvotes: 3

Related Questions