【问题标题】:Fill in missing enumeration values in table (R)填写表(R)中缺失的枚举值
【发布时间】:2020-12-30 09:46:20
【问题描述】:

我想在表格的一列中填写缺失值。在combName 列中,值应该上升到20-400 并继续21-121-400 等等。对于每个缺失值,都应创建一个新行,该行的值按正确的枚举顺序排列,该行的所有其他字段为 0。

   combName sumLength RootID
   <chr>        <dbl>  <int>
 1 20-1          8.05      1
 2 20-2          4.61      1
 3 20-3         14.5       1
 4 20-8          2.29      1
 5 20-10        14.7       1
 6 20-11        23.0       4
 7 20-12        17.0       5
 8 20-13        66.9      14
 9 20-14        39.1       9
10 20-15        12.5       6
# ... with 1,099 more rows

你有什么想法吗?

【问题讨论】:

    标签: r enumeration


    【解决方案1】:

    您可以借助 tidyr 库中的函数来实现此目的。

    combName 分成两列,在'-' 上分割。对于col1 中的每个值,在col2 中创建从1 到400 的行,最后将col1col2 再次组合成一列。

    library(tidyr)
    
    df %>%
      separate(combName, c('col1', 'col2'), sep = '-', convert = TRUE) %>%
      complete(col1, col2 = 1:400, fill = list(sumLength = 0, RootID = 0)) %>%
      unite(combName, col1, col2, sep = '-')
    

    【讨论】:

      【解决方案2】:

      我们使用来自base Rexpand.grid 创建完整的组合数据集

      full_dat <- data.frame(combName = do.call(paste, c(expand.grid(Var1 = 
        sub("-.*", "", unique(df$combName)), Var2 = 1:400), sep="-"))
      

      merge 与原始数据集

      out <- merge(full_data, df, by = "combName", all.x = TRUE)
      out[is.na(out)] <- 0
      

      【讨论】:

        猜你喜欢
        • 2021-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-26
        • 2021-10-12
        • 2019-01-29
        • 1970-01-01
        相关资源
        最近更新 更多