Sverre
Sverre

Reputation: 757

String as factor in R

When creating a data frame in R, strings are by default converted to factors (which I don't mind). But when I want to create a new row to my data frame, I can't find a way to encode a string as a factor. If I use factor(), the string is converted to a numeral, but is still not a factor. Under either scenario, I can't append my new row to the data frame because the new row is not a factor. What I want is to have my new row behave just like my data frame, that is with a string converted to a factor.

> data.frame(c("Name one", "Name two")) -> my.data
> colnames(my.data) <- "Names"
> is.factor(my.data$Names)
[1] TRUE
> new.row1 <- c("Name three")
> is.factor(new.row1)[1]
[1] FALSE
> new.row2 <- c(factor("Name three"))
> new.row2
[1] 1
> is.factor(new.row2)[1]
[1] FALSE
> rbind(my.data, new.row1)
     Names
1 Name one
2 Name two
3     <NA>
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = "Name three") :
  invalid factor level, NA generated
> rbind(my.data, new.row2)
     Names
1 Name one
2 Name two
3     <NA>
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = 1L) :
  invalid factor level, NA generated
> 

Upvotes: 6

Views: 12060

Answers (2)

storaged
storaged

Reputation: 1857

Maybe something like this is going to help you?

data.frame(c("Name one", "Name two")) -> my.data
colnames(my.data) <- "Names"

rbind(my.data, data.frame(Names="name three"))

Upvotes: 1

Henrik
Henrik

Reputation: 14450

The trick is to only rbind a data.frame with another data.frame and not, as you have done, with a simple vector:

my.data <- data.frame(Names = c("Name one", "Name two"))
new.row1 <- data.frame(Names = c("Name three"))
rbind(my.data, new.row1)

##        Names
## 1   Name one
## 2   Name two
## 3 Name three

Upvotes: 10

Related Questions