代码之家  ›  专栏  ›  技术社区  ›  Faryan

如何使用R[关闭]将列表表的名称插入到列中

  •  -3
  • Faryan  · 技术社区  · 6 年前

    我有如下数据:

    # Data
    varx1 <- data.frame(datex = c("2018/01/01","2018/01/02","2018/01/03"), x = c(101,102,103)) 
    varx2 <- data.frame(datex = c("2018/01/01","2018/01/02","2018/01/03","2018/01/04","2018/01/05"), x = c(10,11,12,13,14))
    varx3 <- data.frame(datex = c("2018/01/01"), x = c(1000))
    combination <- list(`code status OK01` = varx1, `code trx OCS02` = varx2, `Revenue 101` = varx3)
    combination
    

    我想得到这样的结果:

    # Result
    result <- data.frame(datex = c("2018/01/01","2018/01/02","2018/01/03","2018/01/01","2018/01/02","2018/01/03","2018/01/04","2018/01/05","2018/01/01"),
                     combination = c("code status OK01","code status OK01","code status OK01","code trx OCS02","code trx OCS02","code trx OCS02","code trx OCS02","code trx OCS02","Revenue 101"),
                     x = c(101,102,103,10,11,12,13,14,1000))
    result
    

    需要此问题的帮助。谢谢

    1 回复  |  直到 6 年前
        1
  •  0
  •   Stephan    6 年前

    我不知道变量 varx3 ,但这将起作用:

    library(tidyverse)
    result <- varx1 %>%
      mutate(combination="code status OK01") %>% 
      bind_rows(varx2 %>% 
                  mutate(combination="code trx OCS02")) %>% 
      bind_rows(varx3 %>% 
                  mutate(combination="Revenue 101")) %>% 
      select(datex, combination, x)
    result
    

    如果要在列表中工作(假设列表是静态的):

    library(tidyverse)
    result <- combination[[1]] %>% 
      mutate(combination="code status OK01") %>% 
      bind_rows(combination[[2]] %>% 
                  mutate(combination="code trx OCS02")) %>% 
      bind_rows(combination[[3]] %>% 
                  mutate(combination="Revenue 101")) %>% 
      select(datex, combination, x)
    result
    

    您指出,您有100多个变量。所以如果你有 combination dataframe包含100个变量,每个变量位于大型列表中的单个dataframe中,您可以使用:

    library(tidyverse)
    var_names <- names(combination)
    df <- NULL
    for (i in 1:length(var_names)) {
      df[[i]] <- combination[[i]] %>%
        mutate(combinate=var_names[[i]])
    }
    result <- bind_rows(df)
    result