
の続きです。前回はCSVファイルをRに読み込ませました。今回は読み込んだデータの体裁を整えましょう。
まず、会社の名前から、"株式会社"を削除します。str_remove()関数を使います。

次は会社の所在地から都道府県名だけの列を作ります。

次は、渋谷区とか札幌市などを取り出しましょう。

prefはlocationのはじめの3文字なので、神奈川県、鹿児島県は、cityのはじめの文字が"県"になってしまっているはずです。確認してみましょう。

prefが神奈川県か鹿児島県ならcityの2文字目からに変換すればいいですね。
と、こここまで書きましたが、和歌山県もありましたね。

mutate()関数とif_else()関数を使いましょう。

うまくできたか確認します。

うまくできました。
仕上げにこれら3つに"県"を追加して、locationは削除しましょう。

"県"が追加されているか確認します。

"県"が追加されましたね。ようやくlocationをpref, cityに分割する作業が終わりました。
次に、typeをみてみましょう。

"特定", "事業者", "排出者"は削除しても意味が通りますね。

次はsectorを見ましょう。

化学工業のセクターが一番多いですね。あんまり文字数が多いと大変なので、10文字目までにします。

現在のdfの見た目を確認します。

少し列の表示順を変えます。

これで、データフレームが整いました。
今回は以上です。
次回は
です。
はじめから読むには、
です。
今回のコードは以下になります。
#
# "株式会社"を削除
df <- df_raw |>
mutate(name = str_remove(name, "株式会社"))
df
#
# locationのはじめの3文字を別の変数に
df <- df |>
mutate(pref = str_sub(location,
start = 1,
end = 3))
df |> select(location, pref)
#
# locationの4文字目以降を別の変数に
df <- df |>
mutate(city = str_sub(location, start = 4))
df |> select(location, pref, city)
#
# 神奈川、鹿児島の確認
df |>
filter(pref == "神奈川") |>
select(location, pref, city)
df |>
filter(pref == "鹿児島") |>
select(location, pref, city)
#
# 和歌山県の確認
df |>
filter(pref == "和歌山") |>
select(location, pref, city)
#
# 神奈川、鹿児島、和歌山のcityのはじめの"県"を削除
df <- df |>
mutate(
city = if_else(
pref %in% c("神奈川", "鹿児島", "和歌山"),
str_sub(city, start = 2),
city
)
)
#
# 神奈川のcity
df |>
filter(pref == "神奈川") |>
select(location, pref, city)
#
# 鹿児島のcity
df |>
filter(pref == "鹿児島") |>
select(location, pref, city)
#
# 和歌山のcity
df |>
filter(pref == "和歌山") |>
select(location, pref, city)
#
# 神奈川を神奈川県に、鹿児島を鹿児島県に、和歌山を和歌山県に
df <- df |>
mutate(pref = if_else(
pref %in% c("神奈川", "鹿児島", "和歌山"), #3つの県なら
str_c(pref, "県"), # "県" を追加
pref # その他は、そのまま
)
) |>
select(-location) # locatiionは削除
#
# 県が追加されているか確認
df |> filter(pref %in% c("神奈川県", "鹿児島県", "和歌山県")) |>
group_by(pref) |>
summarize(n = n())
#
# typeの種類
df |> group_by(type) |>
summarize(n = n())
#
# typeの"特定", "事業者", "排出者"を削除
df <- df |>
mutate(type = str_remove(type, "特定")) |>
mutate(type = str_remove(type, "事業者")) |>
mutate(type = str_remove(type, "排出者"))
df |>
group_by(type) |>
summarize(n = n())
#
# sectorの種類
df |>
group_by(sector) |>
summarize(n = n()) |>
arrange(desc(n))
#
# sectorははじめの10文字だけにする
df <- df |>
mutate(sector = str_sub(sector, 1, 10))
df |>
group_by(sector) |>
summarize(n = n()) |>
arrange(n)
#
# 現在のdfの見た目
df
#
# 列の表示順を変更
df <- df |>
select(year, code, tCO2, type, pref, city, name, sector)
df
#
(冒頭の画像は、Bing Image Creator で生成しました。プロンプトは、beautiful landscape picture, close up of yellow rose flowers, fine bule sky, very natural land, photo です。)