-3

I have data like this:

# 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

I want to have the result like this:

# 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

Need help for this problem. Thanks

Faryan
  • 409
  • 3
  • 11

1 Answers1

0

I don't know the variable varx3, but that will work:

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

if you want to work in your list (given the list is static):

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

You pointed out, you have more than 100 variables. So if you have the combination dataframe with 100 variables, each in a single dataframe in a large list, you can use:

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
Stephan
  • 2,056
  • 1
  • 9
  • 20