> test <- data.frame()
> test<-rbind(test,c("hi","i","am","bob"))
> test<-rbind(test,c("hi","i","am","alice"))
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = "alice") :
invalid factor level, NAs generated
为什么这个最小的例子会产生错误?我想将几个字符串行附加到空数据框。
答案 0 :(得分:7)
您可以将信息存储在字符矩阵中。当然,您可以使用as.data.frame
和参数stringsAsFactors = FALSE
将此矩阵转换为数据框。
> test <- matrix(c("hi","i","am","bob"), nrow = 1)
> test <- rbind(test, c("hi","i","am","alice"))
> test
[,1] [,2] [,3] [,4]
[1,] "hi" "i" "am" "bob"
[2,] "hi" "i" "am" "alice"
> testDF <- as.data.frame(test, stringsAsFactors = FALSE)
> testDF <- rbind(testDF, c("hi","i","am","happy"))
> testDF
V1 V2 V3 V4
1 hi i am bob
2 hi i am alice
3 hi i am happy
答案 1 :(得分:4)
问题在于,默认情况下,R将字符理解为因子。 为了避免这种行为:
options(stringsAsFactors = FALSE)
test <- data.frame()
test<-rbind(test,c("hi","i","am","bob"))
test<-rbind(test,c("hi","i","am","alice"))