read.csv() is a wrapper function for read.table() that mandates a comma as separator and uses the input file's first line as header that specifies the table's column names. Thus, it is an ideal candidate to read CSV files.
#
# Compare with -> read.fwf (for reading «fixed width field» files).
#
# S.a. -> write.csv()
#
# Use -> names to show column-names of csv.
#
# Assume data.csv with a header and values
# to be seperated by commas (","):
data <- read.csv("data.csv")
cat("\n\n")
show(data)
# col_1 col_2 col_3
# 1 foo bar baz
# 2 one two three
cat("\n\n\n")
data$col_1
# [1] foo one
# Levels: foo one
cat("\n\n\n")
# Read a semicolon seperated file:
data_ssv <- read.csv("data-no-header.ssv", head=FALSE, sep=";")
show(data_ssv)
#
# V1 V2 V3
# 1 foo bar baz
# 2 1 2 3
# 3 orange banana
With the text= parameter of read.csv(), it's possible to assign the value for a data frame from data that is embedded within an R source (script) file:
inline_data <- read.csv(text =
"head 1,head 2,head 3
val 1,val 2,val 3
foo,bar,baz"
);
inline_data;
#
# head.1 head.2 head.3
# 1 val 1 val 2 val 3
# 2 foo bar baz