-3

i have a list of 18 . each data frame in the list contains 25 rows and 18 columns.i have a vector of companies for this 18 data frames i need to add a new column to each list in the data frame such that the first column of each data frame should be the company name. First data frame should have the first column as the first company name, second data frame with second company name etc. the company name should be written in all the rows of the respective data frames. How to do this?

Nithin .M
  • 85
  • 5
  • Please provide a reproducible example: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – yarnabrina Jun 24 '19 at 05:41
  • set.seed(1234) Dates <- seq(as.Date("1990-01-01"), as.Date("1994-12-31"), by = "month") n <- length(Dates) df_list <- lapply(1:15, function(i){ tmp <- matrix(rnorm(5*n), ncol = 5) tmp <- apply(tmp, 2, cumsum) colnames(tmp) <- paste0("Var", 1:5) tmp <- as.data.frame(tmp) tmp$Date <- Dates tmp }) – Nithin .M Jun 24 '19 at 06:35
  • The above code can be used to create an example type data.. To this i need to add a column company name to each data frame of the list. I have the company names in another vector. But first dataframe should have first element of the vector as copmany name and so on. now company name should be in the first column with heading company and the name of the company in all the rows of first column of the dataframe – Nithin .M Jun 24 '19 at 06:38
  • You should add this example to your question. This code is not copy-paste friendly. If you present codes in such a way, please add `;` in between lines. And, please try to provide a **minimal** example. – yarnabrina Jun 24 '19 at 07:57

1 Answers1

0

Suppose the vector containg the company names is df_vector. Then you can use purrr::map2(df_vector, df_list, cbind). It will create a list of same number of components as that of df_list (here 15), and all those dataframes will have the first column as the corresponding company name.

In the following illustration, I assumed the names to be the 1st 15 letters.

set.seed(seed = 1234)

Dates <- seq(from = as.Date(x = "1990-01-01"),
             to = as.Date(x = "1994-12-31"),
             by = "month")
n <- length(x = Dates)

df_list <- lapply(X = 1:15,
                  FUN = function(i)
                  {
                    tmp <- matrix(data = rnorm(n = 5 * n),
                                  ncol = 5)
                    tmp <- apply(X = tmp,
                                 MARGIN = 2,
                                 FUN = cumsum)
                    colnames(x = tmp) <- paste0("Var", 1:5)
                    tmp <- as.data.frame(x = tmp)
                    tmp$Date <- Dates
                    tmp
                  })

df_vector <- letters[1:15]

purrr::map2(.x = df_vector,
            .y = df_list,
            .f = cbind)

Hope this helps.

yarnabrina
  • 1,561
  • 1
  • 10
  • 30