データハンドリング系の自作関数
データハンドリングするときに良く使っている自作関数をアップします。
中には自分が関数を知らないだけのものもあるかも。。
Comma <- function(Number){ #---数値をカンマ区切りにする(12桁まで対応) if(nchar(Number) < 4) Temp <- Number if(nchar(Number) == 4) Temp <- paste(substr(Number, 1, 1), ",", substr(Number, 2, 4), sep = "") if(nchar(Number) == 5) Temp <- paste(substr(Number, 1, 2), ",", substr(Number, 3, 5), sep = "") if(nchar(Number) == 6) Temp <- paste(substr(Number, 1, 3), ",", substr(Number, 4, 6), sep = "") if(nchar(Number) == 7) Temp <- paste(substr(Number, 1, 1), ",", substr(Number, 2, 4), ",", substr(Number, 5, 7), sep = "") if(nchar(Number) == 8) Temp <- paste(substr(Number, 1, 2), ",", substr(Number, 3, 5), ",", substr(Number, 6, 8), sep = "") if(nchar(Number) == 9) Temp <- paste(substr(Number, 1, 3), ",", substr(Number, 4, 6), ",", substr(Number, 7, 9), sep = "") if(nchar(Number) == 10) Temp <- paste(substr(Number, 1, 1), ",", substr(Number, 2, 4), ",", substr(Number, 5, 7), ",", substr(Number, 8, 10), sep = "") if(nchar(Number) == 11) Temp <- paste(substr(Number, 1, 2), ",", substr(Number, 3, 5), ",", substr(Number, 6, 8), ",", substr(Number, 9, 11), sep = "") if(nchar(Number) == 12) Temp <- paste(substr(Number, 1, 3), ",", substr(Number, 4, 6), ",", substr(Number, 7, 9), ",", substr(Number, 10, 12), sep = "") if(nchar(Number) > 12) Temp <- Number Temp } WideVar <- function(UseVar){ #---横並びにする関数(WideVarDataの中で使う) for(i in 1:length(UseVar)){ if(i == 1) Output <- paste("1.", UseVar[1], sep="") if(i != 1) Output <- paste(Output, " ", i, "." , UseVar[i], sep="") } Output } WideVarData <- function(UseVar2, UseID, Names = ""){ #---UseID毎にNamesの名前を付けて横並びにする Temp <- gsub("NA", "", tapply(UseVar2, UseID, WideVar)) Temp <- data.frame(Temp, ID = names(Temp)) names(Temp) <- Names Temp } Seireki <- function(UseVar){ #---日付の和暦を西暦に変換する Temp <- ifelse(UseVar < 2000000, 18670000 + UseVar - 1000000, ifelse(UseVar < 3000000, 19110000 + UseVar - 2000000, ifelse(UseVar < 4000000, 19250000 + UseVar - 3000000, 19880000 + UseVar - 4000000))) Temp } Sort <- function(UseData, SortVar, Rev=1){ #---昇順 if(Rev == 1) SortList <- order(SortVar) #---降順 if(Rev == 2) SortList <- rev( order(SortVar) ) UseData[SortList, ] } ExtractVector <- function(UseData, ExVar){ #---ベクトルの状態でExVar毎に最も一番上の値を抜粋する Seq <- sequence(table(ExVar)) UseData[Seq == 1] } ExtractData <- function(UseData, ExVar){ #---データの状態でExVar毎に最も一番上の値を抜粋する Seq <- sequence(table(ExVar)) UseData[Seq == 1, ] }