Home > Back-end >  Initializing list of dataframes with their names and with content
Initializing list of dataframes with their names and with content

Time:09-27

I want to initialize several datasets with a default data.frame, and write them with their respective name to a folder. Also, I want to keep dataframes inside a list so I can loop them afterward.

I already know how to initialize dataframes inside a list:

dataset_default <- data.frame(a = as.character(),
                              b = as.character())

list_of_datasets <- list(first <- dataset_default,
                         second <- dataset_default)

But then if I want to write them to a specific folder with a specific name looping the list, I cannot manage to print the names of the dataframes.

Instead of having to write:

write_tsv(first, "mydata/first.tsv")
write_tsv(second, "mydata/second.tsv")

I would like to have something like this:

for (dataset in list_of_datasets){
    write_tsv(dataset, "mydata/{nameofdataframe}.tsv")

I have seen in other posts that one way of doing it is by initializing the dataframes outside of the list, and then assigning the name to the dataframe inside the list.

first_dataset <- dataset_default
second_dataset <- dataset_default
list_of_datasets <- list(first = first_dataset,
                         second = second_dataset)

In this way, I would be able to use names() over the list and obtain the strings "first" and "second" that I would like to have in my pathways.

What I want to know is if there is a simpler way to do it such as:

#Not working at all
list(first = first_dataset = dataset_default,
     second = second_dataset = dataset_default)

This is an example with 2, but my task consists on writing a total of 30 datasets.

Any ideas?

CodePudding user response:

If I have understood your request correctly, I suggest you the following solution.

REPREX :

# Creating a dataset for the demonstration 
list_of_datasets <- list(first <- mtcars,
                         second <- mtcars,
                         third <- mtcars)


# Naming each dataframe in the list
names(list_of_datasets) <- c("first", "second", "third")


# Writing each dataframe in your working directory with their name as filename

for (i in seq(list_of_datasets)){
  write.table(list_of_datasets[[i]], paste0(names(list_of_datasets)[[i]],".tsv"), sep="\t")
}

Created on 2021-09-26 by the reprex package (v0.3.0)

  • Related