【问题标题】:removing levels from dataframe failed从数据框中删除级别失败
【发布时间】:2015-09-28 13:37:17
【问题描述】:

我正在尝试对数据框列进行计算,但由于该列包含级别,尽管我使用了 droplevels 命令(来自this 帖子),但它们一直失败。我在这里做错了什么:

csv <- data.frame(col1 = c("question",1,23,2,5,6), col2 = c("question",5,6,7,3,""))
csv[csv==''] <- NA
csv <- csv[-c(1),] #remove the header question row because this screws up numeric calculations
csv <- droplevels(csv)
csv[,1] <- 7-csv[,1]

我明白了:

Warning message:
In Ops.factor(7, csv[, 1]) : ‘-’ not meaningful for factors

【问题讨论】:

    标签: r


    【解决方案1】:

    降低等级是一种不同的命令。您不再需要因子。尝试as.numeric(as.character(mycol)) 为算术准备列。

    csv[] <- lapply(csv, function(x) as.numeric(as.character(x)))
    

    我将它包装在lapply 中以转换所有列。

    结果:

    csv[,1] <- 7-csv[,1]
      col1 col2
    2    6    5
    3  -16    6
    4    5    7
    5    2    3
    6    1   NA
    

    当我们有未使用的因素时,我们会降低水平。不要将它们转换为数字。示例:

    fac <- factor(c("a", "b")) #factor with two levels 'a' and 'b'
    fac
    #[1] a b
    #Levels: a b
    
    fac.one <- fac[1] #Just the first element of 'fac' which is 'a'.
    fac.one
    #[1] a
    #Levels: a b       # <-- There are still two levels. 'b' is not used.
    

    当我们创建fac.one 时,我们只有一个元素。但旧的因素水平仍然存在。如果我们只想要对象中正在使用的因素,我们可以像这样使用droplevels:

    droplevels(fac.one)
    #[1] a
    #Levels: a     #One factor remains. 'b' is dropped
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-09
      • 2014-03-09
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      相关资源
      最近更新 更多