Reputation: 603
I tried to rbind a row including a string to a data frame which didnt work. Code:
df1 = data.frame(id=1:5, name=c("peter","kate","lisa","daniel","paul"))
df2 = data.frame(id=5:1, age=c(11,24,25,67,2))
df3 = merge(df1,df2)
df3 = rbind(df3, c(6, "hannah", 30))
df3
str(df3)
Result:
> df1 = data.frame(id=1:5, name=c("peter","kate","lisa","daniel","paul"))
> df2 = data.frame(id=5:1, age=c(11,24,25,67,2))
> df3 = merge(df1,df2)
> df3 = rbind(df3, c(6, "hannah", 30))
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = "hannah") :
ungültiges Faktorniveau, NA erzeugt
> df3
id name age
1 1 peter 2
2 2 kate 67
3 3 lisa 25
4 4 daniel 24
5 5 paul 11
6 6 <NA> 30
>
> str(df3)
'data.frame': 6 obs. of 3 variables:
$ id : chr "1" "2" "3" "4" ...
$ name: Factor w/ 5 levels "daniel","kate",..: 5 2 3 1 4 NA
$ age : chr "2" "67" "25" "24" ...
I looks like R made the name column a Factor column which is why it doesnt accept the string value. How do I solve this? Which is more advisable: convert the whole column into a string column (if this exists) or convert the new string into a factor? How to do this?
Thanks!
Upvotes: 0
Views: 1616
Reputation: 186
A good solution is to use the dplyr package and to create tibbles instead of data frames (a tibble is a modern type of data frame which creates character variables as standard and not factors).
library(dplyr)
df1 <- tibble(id=1:5, name=c("peter","kate","lisa","daniel","paul"))
df2 <- tibble(id=5:1, age=c(11,24,25,67,2))
df3 <- left_join(df1,df2) #or merge(df1, df2) as you prefere so
df3 <- rbind(df3, c(6, "hannah", 30))
df3
str(df3)
Upvotes: 1