【问题标题】:R: efficient way of assigning factor levelsR:分配因子水平的有效方法
【发布时间】:2015-08-13 01:57:26
【问题描述】:

我有一个因子向量。有些值可以重复。这些值事先不知道,但可以排序。例如,

x1 <- factor(c("A", "C", "C", "A", "B" ), levels=c("A", "B", "C"))
x2 <- factor(c("E", "C", "C", "D", "B" ), levels=c("B", "C", "D", "E"))

我想创建另一个向量,其中每个值都是“last”、“other”或“first”,并且这些值对应于第一个或最后一个因子级别。在上述情况下,结果向量 y1 必须是 c("first", "last", "last", "first", "other"),而 y2 必须是 c("last", "other", "other", "other", "first")

目前,我是这样做的:

f2l <- function(x) {
  x <- as.numeric(x)
  y <- rep("other", length(x))
  y[ x == max(x) ] <- "last"
  y[ x == min(x) ] <- "first"
  y
}

这按预期工作,但我想知道是否有更有效的解决方案。

【问题讨论】:

  • 你可以考虑使用data.tablea la进行一种合并

标签: r


【解决方案1】:

您可以使用列表重新分配级别标签。

x1 <- factor(c("A", "C", "C", "A", "B" ), levels=c("A", "B", "C"))
x2 <- factor(c("E", "C", "C", "D", "B" ), levels=c("B", "C", "D", "E"))

f2l <- function(x){
  levels(x) <- list("first" = levels(x)[1],
                    "other" = levels(x)[-c(1, nlevels(x))],
                    "last" = levels(x)[nlevels(x)])
  x
}

f2l(x1)
f2l(x2)

【讨论】:

    【解决方案2】:

    除了Benjamin的方法,如果你确定层数会超过2,你可以使用

    f2l <- function(x){
        levels(x) <- c("first",rep("other",length(levels(x))-2),"last");
        x
    }
    

    如果您为许多factors 这样做,那么与上述方法相比,本杰明的方法很慢。 100000次重复的次数是

    Benjamin
     user  system elapsed 
    26.58    0.00   26.68 
    
    Saksham
    user  system elapsed 
    17.15    0.08   18.30 
    

    【讨论】:

      猜你喜欢
      • 2016-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      相关资源
      最近更新 更多