Skip to content

Input and output

morota edited this page Dec 19, 2012 · 1 revision

Source() a few lines of code

cat("print(1)\nprint(2)\nprint(3)\nprint(4)\nprint(5)\nprint(6)\n", file="hoge.r")
source(pipe("sed -n 3,5p hoge.r"))
[1] 3
[1] 4
[1] 5

source(textConnection(readLines("hoge.r")[3:5]))
[1] 3
[1] 4
[1] 5

File manipulation

# list the files in a directory ($ ls)
list.files()
list.files(pattern= "hoge$")

# Display a file ($ less or lv)
file.show("~/hoge.txt")

# check if the file exists
file.exists("~/hoge.txt)"

# Create an empty file ($ touch hoge.txt)
file.create("~/hoge.txt")

# Remove files ($ rm)
file.remove("a.txt", "b.txt")

# Rename file ($ mv)
file.rename("a.txt", "c.txt")

# Copy file ($ cp)
file.copy("a.txt", "d.txt")

# Extract file information
file.info("a.txt")

# Create a directory
dir.create("hw5") 

# delete a file
unlink("hoge.txt")

# delete a directory
unlink("PathTotheDrectory", recursive=TRUE)

# dowonload a file (wget)
download.file("http://www.ansci.wisc.edu/morota/index.html", destfile="index.html") 

Read pasted data in an email

dat <- read.table(textConnection("PASTE DATA here"), header=TRUE)
closeAllConnections()

Read in multiple files

# ex1
for(i in 1:3) {
  assign(x = paste("data", i, sep = "_"), value =
  read.csv(paste("data", i, ".txt", sep = '')))
}

#ex2
dat <- lapply(1:3, function(x) {read.csv(paste("data", x, ".txt", sep = ''))})

#ex3
x <- 1:3
sprintf("dat%d.txt", x)
[1] "dat1.txt" "dat2.txt" "dat3.txt"
sprintf("dat%d", x)
[1] "dat1" "dat2" "dat3"
filenames <- sprintf("dat%d.txt", x)
varnames <- sprintf("dat%d", x)
for (i in 1:3) {
   var <- read.table(filenames[i])
   assign(varnames[i], var)
}

Read only particular columns

cat("1 2 3 \n4 5 6 \n7 8 9 \n10 11 12\n", file="hoge.txt")
file.show("hoge.txt")
read.table("hoge.txt", colClasses=c("NULL", "numeric", "NULL"), header=TRUE)
  X2
1  5
2  8
3 11
read.table("hoge.txt", colClasses=c("NULL", NA, "NULL"), header=TRUE)
  X2
1  5
2  8
3 11

tempfile() and tempdir()

cat("rnorm(10)\n", file=file.path(tempdir(), 'hoge.R'))
file.show(file.path(tempdir(), 'hoge.R'))
a <- readLines(file.path(tempdir(), 'hoge.R'))
eval(parse(text=a))
 [1] -0.204691 -0.775164  1.275246  0.976682 -1.129983 -0.301754 -0.560835
 [8] -1.128147  0.027111  1.102097

Read a file with unequal row length

cat("1 2 3\n4 5 6 7\n8 9 10\n", file=file.path(tempdir(), 'hoge.R'))
file.show(file=file.path(tempdir(), 'hoge.R')) 
read.table(file=file.path(tempdir(), 'hoge.R'), header=FALSE, fill=TRUE)
  V1 V2 V3 V4
1  1  2  3 NA
2  4  5  6  7
3  8  9 10 NA

Clone this wiki locally