11.2 On data frames or matrices

  • Read in a file into a data frame with the read.table function:
a <- read.table(file="file.txt")

You can convert it as a matrix, if needed, with:

a <- as.matrix(read.table(file="file.txt"))

Useful arguments:

  • Write a data frame or matrix to a file:
write.table(x=a,
    file="file.txt")

Useful arguments:

  • Note that \t stands for tab-delimitation

  • NOTE: read.csv derives from the read.table function, and reads .csv (comma-separated) files. write.csv also exists for writing .csv files.


HANDS-ON

  1. Download inputB.txt the following way, using the download.file function:
download.file(url="https://public-docs.crg.es/biocore/projects/training/R_introduction_2021/inputB.txt",
              destfile = "inputB.txt")
  1. Read in the content of inputB.txt using the read.table command; save in object pop. Note: inputB.txt has a header row!
    What are the dimensions of pop? What are the column names? Check the first rows of pop with the head function.

  2. Select all states that are in the “Eurozone.” What is the total population of the Eurozone, according to this table?

  3. Write to file Eurozone.csv States and Capitals that belong to the “Eurozone.” You need to select rows, as previously done, and also the State and Capital columns.