如何在不清除条目的情况下为分类数据分配级别

问题描述 投票:0回答:1

我有这组数据

BF Condition              SampleID
1 Partially Formula Fed   VD25FE8997
 2 Exclusively Breast Fed  VD25FE8986
 3 Exclusively Breast Fed  VD25FE8974
 4 Exclusively Breast Fed  VD25FE8960
 5 Exclusively Formula Fed VD25FE8951

我想建立三个“级别”,以便使用箱线图运行 Chao1 索引 纯母乳喂养,部分用于 当我拉高级别时,它们显示为“NULL”

# Convert 'category' to factor if it's not already
VitDSI_Data$BFCondition <- factor(VitDSI_Data$BFCondition)

# Add new levels to the 'category' factor
levelsToAdd <- c("Exclusively Breast Fed", "Partially Breast Fed", "Exclusively Formula Fed")
VitDSI_Data$BFCondition <- factor(VitDSI_Data$BFCondition, levels = c(levels(VitDSI_Data$BFCondition), levelsToAdd))

我尝试了这个,但反过来它又清除了环境中的数据。我不确定如何分配级别以获得以下读数(缩短) 是不是我的“级别”作业太长了?

`## [1] 纯母乳喂养 纯配方奶喂养 部分配方奶喂养

级别:纯母乳喂养 纯配方奶喂养 部分配方奶喂养

`

r rstudio
1个回答
0
投票

要么不要重复使用级别,要么使用

union()
代替
c()

> VitDSI_Data$BFCondition <- factor(VitDSI_Data$BFCondition, 
+                                   levels=union(levels(VitDSI_Data$BFCondition), 
+                                                levelsToAdd))
> levels(VitDSI_Data$BFCondition)
[1] "Exclusively Breat Fed"   "Exclusively Formula Fed" "Partially Formula Fed"  
[4] "Exclusively Breast Fed"  "Partially Breast Fed"

数据:

> dput(VitDSI_Data)
structure(list(BFCondition = structure(c(3L, 1L, 1L, 1L, 2L), levels = c("Exclusively Breat Fed", 
"Exclusively Formula Fed", "Partially Formula Fed", "Exclusively Breast Fed", 
"Partially Breast Fed"), class = "factor"), SampleID = c("VD25FE8997", 
"VD25FE8986", "VD25FE8974", "VD25FE8960", "VD25FE8951")), row.names = c("1", 
"2", "3", "4", "5"), class = "data.frame")
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.