String as a factor in R

When creating a data frame in R, the rows are converted to factors by default (which I do not mind). But when I want to create a new row in my data frame, I cannot find a way to encode the row as a factor. If I use factor() , the string is converted to a number, but is still not a factor. In any scenario, I cannot add a new row to the data frame because the new row is not a factor. I want my new row to behave the same as my data frame, that is, with a row 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 > 
+6
source share
2 answers

The trick is only to rbind a data.frame with another data.frame , and not, as you did, 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 
+10
source

Perhaps something like this will help you?

 data.frame(c("Name one", "Name two")) -> my.data colnames(my.data) <- "Names" rbind(my.data, data.frame(Names="name three")) 
+1
source

Source: https://habr.com/ru/post/946401/


All Articles