1. 程式人生 > >R語言實用函式整理

R語言實用函式整理

初始化

options(stringsAsFactors=F,scipen=99)
rm(list=ls());gc()
getwd() 獲得工作路徑資訊
setwd() 設定工作路徑

清空控制檯

快捷鍵control+L

獲取目錄下所有檔名

filenames=dir("/Users/yuyin/Downloads/資料/Excel資料")
##or推薦第二種
setwd("/Users/yuyin/Downloads/資料/Excel資料")
filenames=dir()

讀取檔案輸出檔案

require(data.table)
library(data.table)
da<- fread("/Users/yuyin/Downloads/train_all_weekday.csv"
,header = FALSE) #讀取gbk編碼檔案 u<- read.csv("JData_User.csv",fileEncoding='gbk',header = TRUE) write.table (out, file ="/Users/yuyin/Downloads/2.csv",sep =",",row.names = F,col.names=F,quote =F)

讀寫xlsx檔案

library("xlsx")
t=read.xlsx('吉林2014.xlsx',sheetIndex=1)
write.xlsx(t, file="./s.xlsx")

SQL查詢

library(sqldf)
re=sqldf("select
V1,V2,V6 from da where V2>=20161004 and V2<=20161017 order by V1,V2")

繪圖

library(recharts)
echartr(tmp,as.character(tmp$V2),V6,type = 'line')

分位數

#四個分位數
quantile(ck)  
#自定義分位數 
quantile(ck,  probs = c(0.85,0.95))
median中位數
mean均值

檢視行數

nrow(data.frame)

字串操作

拼接字串

##方法一
paste(Y,'/'
,m,'/',d,sep='') ##方法二 library(stringr) pout=str_c(path,name,collapse='')

替換字串

name=str_replace_all(name,"/","_")

DF去重

tt=unique(tt)

合併資料框

合併行
rbind(t1,t2)
合併列
cbind(t1,t2)

DF排序

x=x[order(x$bad_comment_rate,decreasing=F),]

生成隨機數

runif(n, min=0, max=1) 均勻分佈
rnorm(n, mean=0, sd=1) 正態分佈
sample(seq(0,100,by=1),1,replace=TRUE) 抽樣生成隨機數

最大最小歸一化

b1=(data[,1]-min(data[,1]))/(max(data[,1])-min(data[,1]))  
b1=(d-min(d))/(max(d)-min(d))  

日期轉換

dateChar<-("2014-04-06")
dtV<-as.POSIXct(dateChar,format="%Y-%m-%d")
##或者dtV<-as.Date(dateChar,format="%Y-%m-%d")
format(dtV,"%Y/%m/%d %H:%M:%S")
#轉換為2014/4/6
Y=format(dtV,"%Y")
m=as.character(as.numeric(format(dtV,"%m")))
d=as.character(as.numeric(format(dtV,"%d")))
dt<-paste(Y,'/',m,'/',d,sep='')

計算時間差

d <- c('2013-12-05 18:43:00','2013-08-23 22:29:00')
difftime(d[2],d[1])
difftime(strptime(d, "%Y-%m-%d %H:%M:%S")[2],strptime(d, "%Y-%m-%d %H:%M:%S")[1],units='secs')

高效資料清洗包dplyr代替sqldf

速度比sqldf快很多 適合資料量大處理

library(dplyr)
#將資料整理成的tbl_df資料(處理速度快) 
iris <- tbl_df(iris)
##變數篩選select  對應select  刪除-
select(iris,Sepal.Length,Sepal.Width)
select(iris,-Species)
##對資料運算並新增為新列mutate() 對應 count(a) as t1
mutate(iris,t1=Sepal.Length*2)
##計算
n(): 計算個數
n_distinct() #: 計算 x 中唯一值的個數
first(x), last(x) 和 nth(x, n)#: 返回對應秩的值, 類似於自帶函式 x[1], x[length(x)], 和 x[n]
##過濾filter  對應 where
filter(iris,Sepal.Length>5,Sepal.Width<4)
filter(iris,Sepal.Length>5 & Sepal.Width<4 & (Species == "setosa" | Species == "versicolor"))
##資料排序arrange  對應 order by
arrange(iris,Sepal.Length)
arrange(iris,desc(Sepal.Length))
##彙總group_by() 分組-彙總
group_by(iris, Species)
group_by(iris,Species,Petal.Width)  %>% summarise(c1=n(),c2=n_distinct(Species))
##計算summarise()
summarise(iris,c1=n(),c2=mean(Sepal.Length))
##多步操作連線符%>%
filter(iris,Sepal.Length>5,Sepal.Width<4) %>% summarise(c1=n(),c2=mean(Sepal.Length)) 
##抽樣sample_n sample_frac
sample_n(iris,20) 
##左連線 ab交集 差集
left_join(a, b, by="x1")
right_join(a, b, by="x1")
inner_join(a, b, by="x1")##保留匹配的資料
outer_join(a, b, by="x1")##保留所有資料
semi_join(a, b, by="x1") # 資料集a中能與資料集b匹配的記錄
anti_join(a, b, by="x1") # 資料集a中雨資料集b不匹配的記錄
intersect(x, y): x 和 y 的交集(按行)
union(x, y): x 和 y 的並集(按行)
setdiff(x, y): x 和 y 的補集 (在x中不在y中)
##列合併
bind_cols(y, z)
##行合併
bind_rows(y, z)

查詢相關R包

library(sos)
findFn('onehot')
##具體看sos的help