Export an R list to CSV or Excel
Follow the steps outlined below to print an R list to an comma separated value or Excel file.
Step 1: Create the R list
We will start by writing short R snippet to create a list consisting of a couple of vectors:
language <- c ('Java', 'Python', 'Python', 'Javascript', 'R', 'Javascript')
interviews <- c (188.0, 217.0, 188.0, 171.0, 169.0, 147.0)
interviews_lst <- list (language, interviews)
Step 2: Define the csv or Excel file path
Next we will define the directory, file name and extension in our file system in which we will store your destination csv or Excel file. We will define a variable named file_path to represent the operating system path -in this case it will be a csv file.
file_path <- 'C:\\MyCode\\my_csv_file.csv'
Note: I am using a Windows PC; on macOS or Ubuntu, the file path will be written somewhat differently eg: /myCode/my_csv_file.csv
Step 3: print the list text to the file
Now you are ready to write into the file. We’ll pass the list name and the file location:
capture.output(interviews_lst, file=file_path)
R will now create a file in your operating system and write the list contents.
Step 4: Look into the file contents
Last step will be to simply look into the file contents. Use File Explorer in Windows or Finder on macOS to locate your file and double click it. Here are its contents:
Append a list to an existing CSV or Excel
In this next tutorial, we’ll show how you can append multiple lists to an existing file.
Step 1: Define your list
This is similar to the previous example we showed above:
offices <- c ('Tokyo', 'New York', 'London', 'Paris')
offices_lst <- list (offices)
Step 2: Append into your file
Note the suffix APPEND = TRUE, which opens the file connection for appending and guarantees that the existing content is not overridden.
file_path <- 'C:\\MyCode\\my_csv_file.csv'
capture.output(offices_lst, file=file_path,append = TRUE)
Step 3: Look into the csv file content
Troubleshooting Permission denied errors
In case that R is not able to access the file you are writing into, it will display a permission error in your RStudio console. This could happen in several scenarios:
- The file is opened.
- The file doesn’t exist
- You don’t have permissions to write into the file system directory.
Make sure that your file exists, is not currently opened and that you have access to the directory; and then re-run your code.