How to read and write CSV files in R or import data from and export
data to CSV files in R, using read.csv()
,
read.csv2()
, write.csv()
and
write.csv2()
.
The functions are from the "utils" package, hence, you do not need to do any installation.
Activity | Package | Function |
Read CSV | utils | read.csv() or read.csv2() |
Write CSV | utils | write.csv() or write.csv2() |
read.csv()
and
read.csv2()
, or the differences between
write.csv()
and write.csv2()
below.One of the most common file formats is the comma-separated values file which uses commas to separate the fields.
To read or import CSV or .csv files in R, after setting the working directory to the folder containing the file, use the line of code below:
If your data does not have header, set the
header = FALSE
.
Without setting the working directory, you can use the full file path to read the CSV or .csv file:
If your data uses a comma as decimal point and a semicolon as field
separator, then use the read.csv2()
function instead of read.csv()
which is
for cases where the data uses a period as decimal point and a comma as
field separator.
A cleaner way to read or import files and work with them in R is to assign names to objects. The name "results" will be assigned to the dataframe object below.
Then the dataframe can be viewed by calling the object:
The dataframe named dtfrm will be used:
dtfrm = data.frame(Group = c("A", "B", "B", "C", "D"),
ID = c("A02", "B12", "B15", "C04", "D07"),
Score = c(9, 8, 8, 10, 7),
Position = c(2, 3, 3, 1, 5))
dtfrm
Group ID Score Position
1 A A02 9 2
2 B B12 8 3
3 B B15 8 3
4 C C04 10 1
5 D D07 7 5
To write or export to CSV or .csv files in R to the working directory, use the line of code below:
Or specify the full file path using the location you want to save it:
The output should look like this in Excel:
To remove the row numbers on the first column, set
row.names = FALSE
as shown below.
Or specify a full file path:
write.csv(dtfrm, file = "C:/Users/Public/Statscodes/Rdata/write-files/outdata2.csv", row.names = FALSE)
The output should look like this in Excel:
If you want your data to use a comma as decimal point and a semicolon
as field separator, then use the
write.csv2()
function instead of
write.csv()
which is for cases where you
want the data to use a period as decimal point and a comma as field
separator.
The feedback form is a Google form but it does not collect any personal information.
Please click on the link below to go to the Google form.
Thank You!
Go to Feedback Form
Copyright © 2020 - 2024. All Rights Reserved by Stats Codes