LoginSignup
0
0

ベイズ統計モデリング 写経5

Last updated at Posted at 2024-01-03

3.5 データの読み込みと保存

df = read.csv("c01.csv",fileEncoding = "cp932")
head(df)
##   都道府県コード 都道府県名 元号 和暦.年. 西暦.年. 注 人口.総数. 人口.男. 人口.女.
## 1             00       全国 大正        9     1920      55963053 28044185 27918868
## 2             01     北海道 大正        9     1920       2359183  1244322  1114861
## 3             02     青森県 大正        9     1920        756454   381293   375161
## 4             03     岩手県 大正        9     1920        845540   421069   424471
## 5             04     宮城県 大正        9     1920        961768   485309   476459
## 6             05     秋田県 大正        9     1920        898537   453682   444855

csvを読み込むとdataframe型になる。

class(df)
## [1] "data.frame"
head(df$都道府県名)
## [1] "全国"   "北海道" "青森県" "岩手県" "宮城県" "秋田県"

カラムの書き換え factor型にする。

df$元号 = factor(df$元号, levels = c("大正","昭和","平成"))
head(as.numeric(df$元号))
## [1] 1 1 1 1 1 1

カラムの書き換え。vector型にする。

df$元号 = as.vector(df$元号)
head(df$元号)
## [1] "大正" "大正" "大正" "大正" "大正" "大正"
head(as.numeric(df$元号)) ## エラー
## Warning in head(as.numeric(df$元号)): 強制変換により NA が生成されました

## [1] NA NA NA NA NA NA

3.5.2 データの保存

csvの保存

write.csv(df, file="c01_v2.csv", row.names = FALSE, quote=FALSE, fileEncoding = "cp932")

Rdata形式での保存。型の情報が保存される。

save(df, file="c01_v2.Rdata")

Rdata形式の読み込み。変数に代入する必要はない

load("c01_v2.Rdata")
0
0
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
0
0