【问题标题】:Looping through columns and duplicating data in R循环遍历列并在 R 中复制数据
【发布时间】:2018-09-13 17:26:05
【问题描述】:

我正在尝试遍历列,如果该列是一整年,则应该重复四次,并重命名为季度

所以这个

2000   Q1-01   Q2-01   Q3-01
   1       2       3       3    

应该变成这样:

Q1-00   Q2-00   Q3-00   Q4-00   Q1-01   Q2-01   Q3-01   
   1       1       1       1       2       3       3

有什么想法吗?

【问题讨论】:

  • 如何定义“年”?大于1900?广告。?公元前? :)
  • 任何有四个数字的东西 :) 即 1999 被复制四次 Q1-99、Q2-99、Q3-99 和 Q4-99

标签: r loops


【解决方案1】:

我们可以使用stringr::str_detect 查找具有 4 位数字的列名,然后从这些列中取出最后两位数字

library(dplyr)
library(tidyr)
library(stringr)
df %>% gather(key,value) %>% group_by(key) %>% 
       mutate(key_new = ifelse(str_detect(key,'\\d{4}'),paste0('Q',1:4,'-',str_extract(key,'\\d{2}$'),collapse = ','),key)) %>% 
       ungroup() %>% select(-key) %>% 
       separate_rows(key_new,sep = ',') %>% spread(key_new,value)

PS:希望你没有大数据集

【讨论】:

    【解决方案2】:

    由于您想要重复的列,您可以重新索引您的数据框,然后更新列名

    df <- structure(list(`2000` = 1L, Q1.01 = 2L, Q2.01 = 3L, Q3.01 = 3L,
        `2002` = 1L, Q1.03 = 2L, Q2.03 = 3L, Q3.03 = 3L), row.names = c(NA,
        -1L), class = "data.frame")
    #> df
    #2000 Q1.01 Q2.01 Q3.01 2002 Q1.03 Q2.03 Q3.03
    #1    1     2     3     3    1     2     3     3
    
    # Get indices of columns that consist of 4 numbers
    col.ids <- grep('^[0-9]{4}$', names(df))
    
    # For each of those, create new names, and for the rest preserve the old names 
    new.names <- lapply(seq_along(df), function(i) {
        if (i %in% col.ids)
            return(paste(substr(names(df)[i], 3, 4), c('Q1', 'Q2', 'Q3', 'Q4'), sep = '.'))
        return(names(df)[i])
    })
    
    # Now repeat each of those columns 4 times
    df <- df[rep(seq_along(df), ifelse(seq_along(df) %in% col.ids, 4, 1))]
    
    # ...and finally set the column names to the desired new names
    names(df) <- unlist(new.names)
    #> df
    #00.Q1 00.Q2 00.Q3 00.Q4 Q1.01 Q2.01 Q3.01 02.Q1 02.Q2 02.Q3 02.Q4 Q1.03 Q2.03 Q3.03
    #1     1     1     1     1     2     3     3     1     1     1     1     2     3     3
    

    【讨论】:

    • 像魅力一样工作,谢谢!我刚改成 return(paste(c('Q1', 'Q2', 'Q3', 'Q4'), substr(names(df)[i], 3, 4), sep = '.')),保持标题行整洁...
    猜你喜欢
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多