R language - Chapter 10 input and output

1. Connect the keyboard to the monitor

1.1 using scan() function

scan() reads from a file or enters a vector with the keyboard

> scan("z1.txt")
Read 4 items
[1] 123   4   5   6

> scan("z2.txt")
Read 4 items
[1] 123.0   4.2   5.0   6.0

> scan("z3.txt")

Error in scan("z3.txt") : scan()need'a real', instead of'abc'

#In the default double mode, an error occurs because the file content is not a numeric value.

> scan("z3.txt",what=" ")
Read 4 items
[1]"abc" "de" "f" "g"

> scan("z4.txt",what=" ")
Read 4 items
[1] "abc" "123" "6"   "y"

#Add the parameter what = "" to indicate that you want to use character mode

scan() separates items with "white space" by default. White space characters include spaces, carriage return / line feed, and horizontal tabs. If it is another separator, you can set another separator with the optional parameter sep

> x1 <- scan("z3.txt",what="")
Read 4 items
> x2 <- scan("z3.txt",what="",sep="\n")
Read 3 items
> x1
[1] "abc" "de"  "f"   "g" 
> x2
[1] "abc"  "de f" "g" 
> x1[2]
[1] "de"
> x2[2]
[1] "de f"

Use the scan() function to read data from the keyboard. Type a blank line to end the input.

> v<-scan("")
1: 1 4 5
4: 5 6 7
7: 8 9
9:  
Read 8 items
> v <- scan("",quiet = TRUE)
1: 1 4 5
4: 5 6 7
7: 8 9
9:  
> 

1.2 using the readline() function

It is very convenient to use the readline() function to input single line data from the keyboard.

> a <- readline()
123
> a
[1] "123"
> a <- readline()
abhdb1221
> a
[1] "abhdb1221"
> a <- readline()
abc def g
> a
[1] "abc def g"
> xm <- readline("type your names: ")
type your names: tiancai
> xm
[1] "tiancai"

1.3 output to display

cat() will be a little easier to use than print(). The contents of cat() output are separated by spaces by default. Or set the sep parameter to another separator.

> x <- 1:3
> cat(x,"abc","de\n")
1 2 3 abc de

# The contents of cat() output are separated by spaces by default
# /n indicates a newline character
> cat(x,"abc","de\n",sep="")
123abcde
> cat(x,"abc","de\n",sep="\n")
1
2
3
abc
de
> x <- c(5,12,13,8,88)
> cat(x,sep=c(".",".",".","\n","\n"))
5.12.13.8
88

2. Read and write files

2.1 read data frame or matrix from file

Don't bother with the files. Look at the teacher's code!

> setwd("D:\\jzamu\\tmp\\amupro\\rpro")
> z <- read.table("z.txt",header=TRUE)
> z
  name age
1 John  25
2 Mary  28
3 Jim  19

> class(z)
[1] "data.frame"

Note that scan() cannot read the data frame correctly here because the values and characters in this file are mixed (including the header). There seems to be no way to read the matrix directly from the file, but it can be easily done with the help of other tools. A simple and quick way is to use scan() to read line by line. Use the byrow option in matrix() to set that the matrix is stored by row, not by column.

> setwd("D:\\jzamu\\tmp\\amupro\\rpro")
> x <- matrix(scan("x.txt"),nrow=3,byrow=TRUE)
Read 9 items
> x
     [,1] [,2] [,3]
[1,]    1    0    1
[2,]    1    1    1
[3,]    1    1    0
> class(x)
[1] "matrix" "array"

We can customize functions:

# Custom function
read.matrix <- function(filename) {
    as.matrix(read.table(filename))
}
> setwd("D:\\jzamu\\tmp\\amupro\\rpro")
> v<-read.matrix("z.txt")
> v
     V1     V2   
[1,] "name" "age"
[2,] "John" "25" 
[3,] "Mary" "28" 
[4,] "Jim"  "19" 
> class(v)
[1] "matrix" "array" 

2.2 reading text files

You can use readLines() to read text files, either one line at a time or all at once.

z.txt
name age
John 25
Mary 28
Jim 19

> v <- readLines("z.txt")
> v
[1] "name age" "John 25"  "Mary 28"  "Jim 19"  
> class(v)   #String vector
[1] "character"

Use the readLines() function to read the contents of the file line by line

> v <- file("z.txt","r")
> readLines(v,n=1)
[1] "name age"
> readLines(v,n=1)
[1] "John 25"
> readLines(v,n=1)
[1] "Mary 28"
> readLines(v,n=1)
[1] "Jim 19"
> readLines(v,n=1)
character(0)

In R, the seek() function is used to realize the "rewind" function: re read the file from the beginning of the file.

> v <- file("z.txt","r")
> readLines(v,n=2)#Note here
[1] "name age" "John 25" 
> seek(con=v,where=0)
[1] 36
> readLines(v,n=1)
[1] "name age"

The where=0 parameter indicates that the file is read from the beginning of the file

2.3 reading Excel files

  • [method 1]
    1. Copy data in Excel file
    2. Run the command in R language environment: read.table("clipboard", header=TRUE)
  • [method 2]
    1. Set the domestic image in the Rstudio environment: Tools > Global Options > packages
    2. Install and run the package readxl for reading Excel files:
    install.packages("readxl")
    library("readxl")
    read_excel("C:\test\me\tmp.xls", sheet=1) or read_excel(“C:/test/me/tmp.xls”)

2.4 reading csv files

read.csv("tmp.csv",header=TRUE)

2.5 accessing files on remote computers via URL s

Some I/O functions, such as read.table() and scan(), can take the website address as a parameter.
For example, we read some data from the University of California Irvine at http://archive.ics.uci.edu/ml/datasets.html , use the Echocardiogram dataset. After visiting the link to browse the page, we find the location of the file, and then read the data with R. The code is as follows:

> uci <- "http://archive.ics.uci.edu/ml/machine-learning-databases/"
> uci <- paste(uci,"echocardiogram/echocardiogram.data",sep="")
> ecc <- read.csv(uci)

2.6R reading of built-in data set

> data()       #View the built-in dataset
> force(iris)           #View the contents of R's own dataset iris

2.7 writing documents

Since R language is mainly used for statistical functions, reading files may be more commonly used than writing files. But writing files is sometimes necessary. Here are some methods to write files.

  • The use of the write.table() function is very similar to read.table(), except that it writes the data frame to the file rather than reads it from the file.
> kids <- c("Jack","Jill")
> ages <- c(12,10)
> #d<- data.frame(kids=c("jack","ji"),ages=c(10,18))
#d
> d <- data.frame(kids,ages)
> d
  kids ages
1 Jack   12
2 Jill   10
> write.table(d,"kds.txt")

# The contents of the file kds.txt are as follows:
"kids" "ages"
"1" "Jack" 12
"2" "Jill" 10

The function cat() can be used to write files, one part at a time.

> cat("abc\n",file="u.txt")
> cat("de\n",file="u.txt",append=TRUE)
#File u.txt content
abc
de

Write a line with the function cat()

> cat(file="v.txt",1,2,3,"abc","xyz\n")
#Contents of file v.txt
1 2 3 abc xyz

Write to the file with the function writeLines().

> v <- file("www.txt","w")      #write
> writeLines(c("abc","de","f"),v)
> close(v)      #Active shutdown
#Contents of the file www.txt
abc
de
f

3. Obtain file and directory information

setwd("")

> ?files

This is the end!!!!!!!!!

Keywords: R Language

Added by mrjonnytou on Mon, 25 Oct 2021 16:11:33 +0300