为了保留已定义变量的类,您必须做两件事:
1) 设置stringsAsFactors = FALSE,这样字符变量就不会成为一个因素。
2) 新行必须是列表。
就像这个例子:
> df.empty <- data.frame(column1 = numeric(), column2 = character(),
+ column3 = factor(levels=c("A","B","C")), stringsAsFactors = FALSE)
>
> newRow <- list(-2, "MyString","B")
> incorrectRow <- list(-2, "MyString", "C")
>
> # Not mess columns names
>
> df.empty[nrow(df.empty) + 1,] <- newRow
> df.empty[nrow(df.empty) + 1,] <- incorrectRow
>
> df.empty
column1 column2 column3
1 -2 MyString B
2 -2 MyString C
> summary(df.empty)
column1 column2 column3
Min. :-2 Length:2 A:0
1st Qu.:-2 Class :character B:1
Median :-2 Mode :character C:1
Mean :-2
3rd Qu.:-2
Max. :-2
为了保留列名,功劳归于这个anwser:
https://stackoverflow.com/a/15718454/8382633
我的第一次尝试也是使用 rbind,但它有一些缺点。它不保留列名,而且,将所有字符串转换为因子,或者如果您设置 stringsAsFactors = FALSE,则将所有因子转换为字符串!!
> df.empty <- rbind.data.frame(df.empty, newRow, incorrectRow)
>
> summary(df.empty)
c..2...2. c..MyString....MyString.. c..B....C..
Min. :-2 MyString:2 B:1
1st Qu.:-2 C:1
Median :-2
Mean :-2
3rd Qu.:-2
Max. :-2
> class(df.empty$c..MyString....MyString..)
[1] "factor"
或使用 stringsAsFactors = FALSE:
> df.empty <- rbind.data.frame(df.empty, newRow, incorrectRow, stringsAsFactors = FALSE)
>
> summary(df.empty)
c..2...2. c..MyString....MyString.. c..B....C..
Min. :-2 Length:2 Length:2
1st Qu.:-2 Class :character Class :character
Median :-2 Mode :character Mode :character
Mean :-2
3rd Qu.:-2
Max. :-2
>
> class(df.empty$c..B....C..)
[1] "character"
我认为它接近重复。但最后,这个问题给我带来了更多的问题。
希望对你有帮助。