【问题标题】:Using factor with levels gives me NA使用带水平的因子给我 NA
【发布时间】:2014-03-21 11:23:27
【问题描述】:

有些事情我想不通
这是我的数据集

 Proband Lauf Interleukin Ansatz    Zeitpunkt  
    1        3    2        IFNy   stim         ZP21
    2        3    2         iL2   stim    ZP4        
    3        3    2         iL2   stim         ZP14  
    4        5    3         iL2   stim         ZP21  
    5        4    3         iL2   stim   ZP2         
    6        4    3         iL2   stim    ZP4        
    7        4    3         iL2   stim        ZP28   
    8        9    5         iL2   stim ZP0           
    9       13    6        IFNy   stim    ZP4        
    10      13    6         iL2   stim      ZP7      
    11      16    7         iL2   stim         ZP21  
    12      16    7         iL2   stim        ZP28   

我想排序到“Zeitpunkt”,所以接下来我做了什么:

pvalsig1 <- read.csv2(file="pvalsig.csv", fill=NA, na.strings="")
pvalsig1 <- pvalsig[,1:5]
pvalsig1$Zeitpunkt <- as.character(pvalsig1$Zeitpunkt)
pvalsig1$Zeitpunkt <- factor(pvalsig1$Zeitpunkt, levels=c("ZP0", "ZP2", "ZP4", "ZP7", "ZP14", "ZP21", "ZP28", "ZP35", "ZPM9", "ZPM9+1"))  

这给了我

Proband Lauf Interleukin Ansatz Zeitpunkt
1        3    2        IFNy   stim      ZP21
2        3    2         iL2   stim      <NA>
3        3    2         iL2   stim      ZP14
4        5    3         iL2   stim      ZP21
5        4    3         iL2   stim      <NA>
6        4    3         iL2   stim      <NA>
7        4    3         iL2   stim      <NA>
8        9    5         iL2   stim      <NA>
9       13    6        IFNy   stim      <NA>
10      13    6         iL2   stim      <NA>
11      16    7         iL2   stim      ZP21
12      16    7         iL2   stim      <NA>  

我敢肯定,这与之前“Zeitpunkt”栏中的不规则排队有关。但我无法弄清楚它是什么以及如何驾驭它。谢谢

【问题讨论】:

    标签: r sorting rank r-factor


    【解决方案1】:

    试试:

    pvalsig1$Zeitpunkt <- factor(gsub("\\s*", "", pvalsig1$Zeitpunkt), levels=c("ZP0", "ZP2", "ZP4", "ZP7", "ZP14", "ZP21", "ZP28", "ZP35", "ZPM9", "ZPM9+1"))
    

    这将从您的列中删除所有空格。您遇到的问题是您尝试使用诸如"ZP0 " 和级别ZP0 之类的值创建一个因子,因此由于额外的空格,这些值不匹配。

    请注意,如果您的因子级别可以包含空格或其他空白字符,这将中断,但如果是这种情况,您可以很容易地将正则表达式调整为:

    "(^\\s+|\\s*$)"
    

    此外,根据您从何处获取此数据,某些输入函数具有去除多余空白的功能(例如,read.table 有一个 strip.white 参数)。

    此外,在 R trim 上的快速搜索会拉出此 popular SO answer

    【讨论】:

    • thx 工作得很好,虽然我不明白你发布的最后一点代码。
    • @newbymedicalstats 这是一种不同的正则表达式模式,只会删除前导或尾随空格。 | 表示“或”,^ 表示开始,&amp; 表示结束。 \\s* 表示任意数量的连续空格。所以整个表达式的意思是“从头匹配任意数量的空格,或者从末尾匹配任意数量的空格”
    猜你喜欢
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2017-12-07
    相关资源
    最近更新 更多