获取<;NA>;使用as.factor()时

获取<;NA>;使用as.factor()时,r,boxplot,na,factors,R,Boxplot,Na,Factors,我试图将data.frame列的每个值转换为因子,这样我就可以将它们用作箱线图中的“组”。但是,使用as.factor()和factor()函数,它将每个值都转换为。该列中有5种不同的细胞类型,CD8、CD4、B细胞、单核细胞、格兰-并且全部变成NA 令人困惑的是,当我将函数仅应用于列的一行时,它就可以很好地工作。数据帧非常大(超过300万行)-这可能是问题的原因吗 代码: > head(BP) Methylation Cell_Type 1 0.03219298 CD

我试图将data.frame列的每个值转换为因子,这样我就可以将它们用作箱线图中的“组”。但是,使用as.factor()和factor()函数,它将每个值都转换为。该列中有5种不同的细胞类型,CD8、CD4、B细胞、单核细胞、格兰-并且全部变成NA

令人困惑的是,当我将函数仅应用于列的一行时,它就可以很好地工作。数据帧非常大(超过300万行)-这可能是问题的原因吗

代码:

> head(BP)
 Methylation Cell_Type
  1  0.03219298       CD8
  2  0.11684228       CD8
  3  0.04214158       CD8
  4  0.26700497       CD8
  5  0.34251732       CD8
  6  0.34231208       CD8

> BP$Cell_Type <- as.factor(BP$Cell_Type)

  > head(BP)
     Methylation Cell_Type
   1  0.03219298      <NA>
   2  0.11684228      <NA>
   3  0.04214158      <NA>
   4  0.26700497      <NA>
   5  0.34251732      <NA>
   6  0.34231208      <NA>

可以先确定
单元格类型
是字符吗

BP <- tibble::tribble(
     ~Methylation, ~Cell_Type,
  0.03219298,  "CD8",
  0.11684228,  "CD8",
  0.04214158,  "CD8",
  0.26700497,  "CD8",
  0.34251732,  "CD8",
  0.34231208,  "CD8")

BP$Cell_Type <- as.factor(BP$Cell_Type)  


print(BP)

Methylation Cell_Type
        <dbl> <fct>    
1      0.0322 CD8      
2      0.117  CD8      
3      0.0421 CD8      
4      0.267  CD8      
5      0.343  CD8      
6      0.342  CD8   


BP可以先确定
Cell\u Type
是字符吗

BP <- tibble::tribble(
     ~Methylation, ~Cell_Type,
  0.03219298,  "CD8",
  0.11684228,  "CD8",
  0.04214158,  "CD8",
  0.26700497,  "CD8",
  0.34251732,  "CD8",
  0.34231208,  "CD8")

BP$Cell_Type <- as.factor(BP$Cell_Type)  


print(BP)

Methylation Cell_Type
        <dbl> <fct>    
1      0.0322 CD8      
2      0.117  CD8      
3      0.0421 CD8      
4      0.267  CD8      
5      0.343  CD8      
6      0.342  CD8   


BP您能将
dput(head(BP))的结果添加到您的问题中吗。如果您查看数据(使用
str(BP)
),您将看到它具有嵌套的数据帧,即
Cell\u Type
是一个数据帧。要使代码正常工作,首先应将其转换为向量。所以使用
BP$Cell\u类型。。。当您执行
str(BP)
时,您会注意到该列已经是嵌套数据帧中的
因子。所以做
BP$Cell\u Type就足够了。你能把
dput(head(BP))的结果添加到你的问题中吗。如果您查看数据(使用
str(BP)
),您将看到它具有嵌套的数据帧,即
Cell\u Type
是一个数据帧。要使代码正常工作,首先应将其转换为向量。所以使用
BP$Cell\u类型。。。当您执行
str(BP)
时,您会注意到该列已经是嵌套数据帧中的
因子。所以做
BP$Cell_Type就足够了,理论上这应该行得通,但是OP的data.frame中可能有一些奇怪的东西,或者列是其他类。理论上这应该行得通,但是OP的data.frame中可能有一些奇怪的东西,或者列是其他类。
BP$Cell_Type <- as.factor(as.character(BP$Cell_Type))