41--ls( )

ls()可以用来列出现存的所有对象。
pattern是一个具名参数,可以列出所有名称中含有字符串“s”的对象。

> ls()
[1] "s"
> ls(pattern = "a")
character(0)
> ls(pattern = "s")
[1] "s"

42--scan()

scan()函数有一个可选参数what用来设定变量的模式(mode),默认为double模式。
由于文件中内容不是数值,所以出现错误。

> scan("z.txt")
Error in scan("z.txt") : scan() expected 'a real', got 'a'
> scan("z.txt", what = "")
Read 3 items
[1] "a" "b" "c"

43--cat()

cat()可以输出多个表达式并且输出内容不带编号。

> x <- 1:3
> cat(x, "abc", 's')
1 2 3 abc s
> cat(x, "abc", 's', sep = "n")
1
2
3
abc
s

cat( )还可以用来写入文件

> cat(x,"n" ,"abc", 's', file = "z.txt")

44--readline()与readLines()

如果想从键盘输入单行数据,readline()函数会非常方便。
prompt为提示语参数

> w <- readline(prompt = "input a number: ")
input a number: 5
> w
[1] "5"

readLines( )可以逐行读取文件。

  • 可以用file()函数建立连接,其中“r”表示read。
  • n = 1 表示一次只读取文件的一行。
> c <- file("z", "r")
> readLines(c, n = 1)
[1] "1 2 3 "
> readLines(c, n = 1)
[1] "abc s"
> readLines(c, n = 1)
character(0)

> close(c)          #用close()来关闭连接
> readLines(c, n = 1)
Error in readLines(c, n = 1) : invalid connection

45--seek()

seek()可以指定文件位置开始读取数据
where = 0指把起始指针指向文件的最开头

> c <- file("z.txt", "r")
> readLines(c, n = 1)
[1] "1 2 3 "
> seek(con = c, where = 0)
[1] 8                          #返回8是指在执行命令前文件指针位于8处,回车占用两个位置
> readLines(c, n = 1)
[1] "1 2 3 "
> readLines(c, n = 1)
[1] "abc s"
> readLines(c, n = 1)
character(0)
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!