【问题标题】:Replacing numbers with a label in DF [duplicate]用DF中的标签替换数字[重复]
【发布时间】:2020-09-02 10:23:54
【问题描述】:

我有一个带有数字的“大小”列的 DF。我想根据范围 small = 1:10 medium = 11:49 large = 50:200 将这些数字替换为 small、medium 或 large。

我尝试过使用

table$Size <- factor(table$Size,
                    levels = c(1:10),c(11:49),c(50:200),
                    labels = c("small"),c("medium"),c("large"))

但我明白为什么这不起作用。 我也尝试过使用 str_replace all 但这也会产生错误。

有没有办法用相应的标签替换这些范围内的数字?

【问题讨论】:

标签: r


【解决方案1】:

cut() 函数将数值变量转换为因子。你可以提供breaks 来告诉你应该在哪里进行削减。这取代了您在levels 的尝试。然后你申请你的labels。您还需要指定一个 right 参数 - 间隔应该在右侧关闭(如果为 false,则在左侧关闭)。

set.seed(10)
x <- sample(1:200, 1000, replace = TRUE)
summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1.00   50.75  101.00  101.57  153.00  200.00 
x <- cut(x, breaks = c(0, 10, 49, 200),
         labels = c("small", "medium", "large"),
         right = TRUE)
summary(x)
 small medium  large 
    51    189    760 

我还想指出您的代码存在的问题。在labels = c("small"),c("medium"),c("large") 行中,c() 之外有逗号。您应该将向量的所有所需元素包含在同一个 c() 中:

 labels = c("small", "medium", "large")

如果逗号在括号之外,R 将仅将c("small") 映射到labels,然后尝试将c("medium") 匹配到函数的下一个参数。

【讨论】:

    【解决方案2】:

    用列表重新编码levels

    table1$Size.fac <- factor(table1$Size)
    
    levels(table1$Size.fac) <- list("small" = 1:10,
                                "medium" = 11:49,
                                "large" = 50:200)
    
    table1
    #   Size Size.fac
    # 1  156    large
    # 2   17   medium
    # 3  128    large
    # 4    7    small
    # 5   77    large
    # 6  112    large
    

    数据:

    table1 <- structure(list(Size = c(156L, 17L, 128L, 7L, 77L, 112L)), row.names = c(NA, 
    6L), class = "data.frame")
    

    【讨论】:

      猜你喜欢
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多