【问题标题】:R override certain columns for child articles in Data FrameR覆盖数据框中子文章的某些列
【发布时间】:2021-11-01 13:14:48
【问题描述】:

我有一个包含逐行产品数据的数据框,包括子文章。现在我想将某些值(列)从父亲转移到所有孩子。

例子:

 data.frame(sku = c("V1000837", "V1000837-001", "V1000837-002", "01549831"),
           height = c(10, 12, NA, 50),
           width = c(15, NA, 15, 150),
           color = c("red", "blue", "green", "black"),
           power = c("12W", NA, NA, "130W"))

    sku height width color power
V1000837     10    15   red   12W
V1000837-001 12    NA  blue  <NA>
V1000837-002 NA    15 green  <NA>
01549831     50   150 black  130W

现在我想将父文章(以 V 开头,不以“-\d{3}”结尾)的列的值接管给所有子项(以 V 开头,以“-\d {3}")。

我只想从父亲那里为关联的孩子接管列“power”和“width”的值。

结果应该是这样的:

sku height width color power
V1000837     10    15   red  12W
V1000837-001 12    15  blue  12W
V1000837-002 NA    15 green  12W
01549831     50   150 black  130W

很遗憾,我没有办法。 感谢您的帮助。

【问题讨论】:

    标签: r dataframe overwrite


    【解决方案1】:

    您可以将"-" 上的数据分成不同的列。按父(父)值和fill powerwidth 列分组。您可以再次unite 值。

    library(dplyr)
    library(tidyr)
    
    df %>%
      separate(sku, c('father', 'child'), sep = '-', fill = 'right') %>%
      group_by(father) %>%
      fill(power, width, .direction = 'updown') %>%
      ungroup %>%
      unite(sku, father, child, na.rm = TRUE, sep = '-')
    
    #  sku          height width color power
    #  <chr>         <dbl> <dbl> <chr> <chr>
    #1 V1000837         10    15 red   12W  
    #2 V1000837-001     12    15 blue  12W  
    #3 V1000837-002     NA    15 green 12W  
    #4 01549831         50   150 black 130W 
    

    【讨论】:

    • 非常感谢您的快速回答。我必须调整什么才能不仅替换 NA 值而且替换空字符串?
    • 将空字符串替换为NA。类似...%&gt;% mutate(across(c(height, weight), ~replace(., . == '', NA))) %&gt;%...
    猜你喜欢
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多