11.1 On vectors
- Read a file as a vector with the scan function
# Read in file
scan(file="file.txt")
# Save in  object
k <- scan(file="file.txt")By default, scans “double” (numeric) elements: it fails if the input contains characters.
If non-numeric, you need to specify the type of data contained in the file:
# specify the type of data to scan
scan(file="file.txt", 
    what="character")
scan(file="~/file.txt", 
    what="character")Regarding paths of files:
If you don’t specify the path, the file is assumed to be located in the current working directory (getwd())
If the file is not in the current directory, you can provide a full or relative path. For example, if located in the home directory, read it as:
scan(file="~/file.txt", 
    what="character")- Write the content of a vector in a file:
# create a vector
mygenes <- c("SMAD4", "DKK1", "ASXL3", "ERG", "CKLF", "TIAM1", "VHL", "BTD", "EMP1", "MALL", "PAX3")
# write in a file
write(x=mygenes, 
    file="gene_list.txt")Regarding paths of files:
When you write a file, without a path, it will be created in the current working directory.
You can also provide a full or relative path:
# Write to home directory
write(x=mygenes,
        file="~/gene_list.txt")
# Write to one directory up
write(x=mygenes,
        file="../gene_list.txt")HANDS-ON
- Download file inputA.txt the following way, using the download.file function:
download.file(url="https://public-docs.crg.es/biocore/projects/training/R_introduction_2021/inputA.txt",
              destfile = "inputA.txt")The file is now in your current working directory. Check with dir() (lists of files and folders).
- Read in the content of inputA.txt using the scan function: save in object z. How many elements does z contain? 
- Sort vector z: save sorted vector in the new object zsorted (see function sort()) 
- Write zsorted content into file outputA.txt, using the write() function.