英文:
Adding factor levels when using rows_append()
问题
当我使用 rows_append()
时,如何添加附加数据的级别以防止此错误:Error in rows_append():! Can't convert from...
。
我希望最终结果包括新组合数据集中的所有级别。
这是一个示例:
library(dplyr)
data1 <- iris[1:100,] %>%
droplevels()
data2 <- iris[101:150,] %>%
droplevels()
dataFull <- data1 %>%
rows_append(data2)
#> Error in `rows_append()`:
#> ! Can't convert from `y$Species` <factor<23909>> to `x$Species` <factor<44a85>> due to loss of generality.
英文:
When I'm using rows_append()
how do I add the levels of my additional data to prevent this error: Error in rows_append():! Can't convert from...
I would like the end result to include all levels in the newly combined data set.
Here's a reprex
library(dplyr)
data1 <- iris[1:100,] %>%
droplevels()
data2 <- iris[101:150,] %>%
droplevels()
dataFull <- data1 %>%
rows_append(data2)
#> Error in `rows_append()`:
#> ! Can't convert from `y$Species` <factor<23909>> to `x$Species` <factor<44a85>> due to loss of generality.
</details>
# 答案1
**得分**: 1
Update removed first answer: (thanks to @Axeman):
我们可以合并因子水平并使它们在数据集之间保持一致
```R
library(dplyr)
levels <- union(levels(data1$Species), levels(data2$Species))
data1$Species <- factor(data1$Species, levels = levels)
data2$Species <- factor(data2$Species, levels = levels)
data1 %>%
rows_append(data2) %>%
str()
'data.frame': 150 obs. of 5 variables:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
$ Species : Factor w/ 3 levels "setosa", "versicolor", ...: 1 1 1 1 1 1 1 1 1 1 ...
英文:
Update removed first answer: (thanks to @Axeman):
We could combine the factor levels and make them consistent across datasets
library(dplyr)
levels <- union(levels(data1$Species), levels(data2$Species))
data1$Species <- factor(data1$Species, levels = levels)
data2$Species <- factor(data2$Species, levels = levels)
data1 %>%
rows_append(data2) %>%
str()
'data.frame': 150 obs. of 5 variables:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论