R語言入門視頻筆記--6--R函數之cat、format、switch函數


一、cat

貓  怎么就變成一個輸出函數了呢?

cat  一個輸出函數,功能和print有相同之處

我們一起比較看看

 

1、cat(“hellow world”)或cat('hellow world')輸出的是:

hello world 1 

 

print("hellow world")或print('hellow world')輸出的是:

[1] "hello world 1 "

 

2、cat(c("AB","C"),c("E","F"),"n",sep = "/")輸出的是AB/C/E/F/n

  print(c("AB","C"),c("E","F"),"n",sep = "/")是不可以的  只能這樣:print(c("AB","C"))

 

3、cat(12,212,31223,file="1.txt")  可以把前面的數字什么的寫入當前工作目錄的1.txt文件中,可以用這個方法把腳本     輸出到文件,加上append=TRUE參數,可以不覆蓋原文件,在后面繼續添加。

  print肯定不行 別試了

 

4、如同上文:cat與format函數連用

    cat(type,"is not recognized type\n")

 

 

二、format

format函數可以將時間格式,調節成指定時間樣式,這是它的功能。

用法實例如下:

 today<-Sys.time()

 

 

 format(as.Date(today),format="%Y")  

[1] "2016"  

 

format(as.POSIXlt(today),format="%Y")  

[1] "2016"  

 

 format(as.POSIXct(today),format="%Y")  

[1] "2016"  

 

三、switch

先舉個栗子

x<-3
 switch(x,2+2,mean(1:10),rnorm(4))   執行的是rnorm(4)

x<-2
 switch(x,2+2,mean(1:10),rnorm(4))  執行的是mean(1:10)

 

 

這你就明白了吧 switch的用法是switch(EXPR,....)

EXPR:可以為一個number或字符串

...:the list of alternatives

若EXPR為字符串,則該list必須具有名字,每個list項為name_i=expr_i,當EXPR與某個name_i嚴格匹配時,expr_i為結果。

若EXPR不為字符串,則強制轉換為integer,后面的list按EXPR取值從1開始對應計算,並作為該函數的結果。

 

再舉個栗子

(1)

for(i in c(-1:3,0)) print(switch(i,1,2,3,4))

結果為

NULL
NULL
[1] 1
[1] 2
[1] 3
NULL

(2)switch("cc",a=10,cc=9,cd=8,d=7)

結果為

9

 

 

今天就到這里吧 休息了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM