1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

R 寄せ集め

Last updated at Posted at 2020-06-17

R言語関係のサンプルコードや情報の寄せ集めです。まとまったら別投稿に分けるかも知れません。

組み込みデータセットを取得する

data(package="datasets")

変数の名前や式のテキストからクラスを取得する

class_from_text <- function(text) {
  class(eval(parse(text=text)))
}

x <- 0
class_from_text("x")
# [1] "numeric

変数の名前や式のテキストからクラスの継承を判定する

inherits_for_text <- function(text, what, which=FALSE) {
  inherits(eval(parse(text=text)), what=what, which=which)
}

x <- 0
inherits_for_text("x", "numeric") # FALSE
inherits_for_text("x", "integer") # TRUE

dplyr、purrr、stringrなどをまとめてインストールする

install.packages("tidyverse", dependencies=TRUE)

文字列の先頭から最初の半角スペースまでを抜き出す。

require(stringr)

str_extract("ab cd", "\\S*") # "ab"
str_extract(" cd", "\\S*")   # ""
str_extract(" ", "\\S*")     # ""
str_extract("", "\\S*")      # ""

変数の名前や式のテキストからクラスを取得する

x <- 0
class(eval(parse(text="x")))

組み込みデータセットの名前を取得する

require(purrr)
require(stringr)

get_data_names <- function(package=NULL) {
  data(package=package)$results[,"Item"] %>%
    purrr::map_chr(~str_extract(., "\\S*"))
}
get_data_names("datasets")
出力抜粋
  [1] "fruit"                 "sentences"             "words"                 "AirPassengers"         "BJsales"              
  [6] "BJsales.lead"          "BOD"                   "CO2"                   "ChickWeight"           "DNase"                
 [11] "EuStockMarkets"        "Formaldehyde"          "HairEyeColor"          "Harman23.cor"          "Harman74.cor"   

組み込みデータセットの名前とクラスを取得する。

データフレームとして取得する。

class()が2つ以上の型名を返したデータセットは型名の数だけデータセットの名前が追加されます。

require(purrr)
require(stringr)

get_data_names <- function(package=NULL) {
  data(package=package)$results[,"Item"] %>%
    purrr::map_chr(~str_extract(., "\\S*"))
}

class_from_text <- function(text) {
  class(eval(parse(text=text)))
}

get_data_names("datasets") %>%
  purrr::map_df(~data.frame(name=., class=class_from_text(.)))
出力抜粋
                     name          class
1                   fruit      character
2               sentences      character
3                   words      character
4           AirPassengers             ts
5                 BJsales             ts
6            BJsales.lead             ts

名前付きリストとして取得する。

require(purrr)
require(stringr)

get_data_names <- function(package=NULL) {
  data(package=package)$results[,"Item"] %>%
    purrr::map_chr(~str_extract(., "\\S*"))
}

class_from_text <- function(text) {
  class(eval(parse(text=text)))
}

names <- get_data_names("datasets")
names %>%
  purrr::map(class_from_text) %>%
  purrr::set_names(names)
出力抜粋
$AirPassengers
[1] "ts"

$BJsales
[1] "ts"

$BJsales.lead
[1] "ts"

$BOD
[1] "data.frame"

$CO2
[1] "nfnGroupedData" "nfGroupedData"  "groupedData"    "data.frame"    

組み込みデータセットのクラスを取得する。

require(purrr)
require(stringr)

get_data_names <- function(package=NULL) {
  data(package=package)$results[,"Item"] %>%
    purrr::map_chr(~str_extract(., "\\S*"))
}

class_from_text <- function(text) {
  class(eval(parse(text=text)))
}

get_data_names("datasets") %>%
  purrr::map(class_from_text) %>%
  purrr::flatten_chr() %>%
  unique
出力
 [1] "character"      "ts"             "data.frame"     "nfnGroupedData" "nfGroupedData"  "groupedData"    "mts"           
 [8] "matrix"         "table"          "list"           "array"          "dist"           "numeric"        "factor"    
  • 注意
    • purrr::map_chr(~class(eval(parse(text=.))))を使用するとclass()が2つ以上の文字列を返したときにエラーが発生します。
    • 一度purrr::map(~class(eval(parse(text=.))))でリストを取得した後、purrr::flatten_chr()でベクトルに戻します。

tsクラスのデータセットの名前を取得する。

require(purrr)
require(stringr)

get_data_names <- function(package=NULL) {
  data(package=package)$results[,"Item"] %>%
    purrr::map_chr(~str_extract(., "\\S*"))
}

inherits_for_text <- function(text, what, which=FALSE) {
  inherits(eval(parse(text=text)), what=what, which=which)
}

get_data_names("datasets") %>%
  purrr::keep(~inherits_for_text(., "ts"))
出力
 [1] "AirPassengers"  "BJsales"        "BJsales.lead"   "EuStockMarkets"
 [5] "JohnsonJohnson" "LakeHuron"      "Nile"           "Seatbelts"     
 [9] "UKDriverDeaths" "UKgas"          "USAccDeaths"    "WWWusage"      
[13] "airmiles"       "austres"        "co2"            "discoveries"   
[17] "fdeaths"        "freeny.y"       "ldeaths"        "lh"            
[21] "lynx"           "mdeaths"        "nhtemp"         "nottem"        
[25] "presidents"     "sunspot.month"  "sunspot.year"   "sunspots"      
[29] "treering"       "uspop" 
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?