LoginSignup
1
0

More than 3 years have passed since last update.

リストにNULLが含まれるとtibbleにできないので、NAに強制変換する

Posted at

TL;DR

NULLが含まれるリストはas_tibble()が使えないので、先にNULLをNAに置換するといいよ

リストをtibbleにしたいが、エラーが出る

スクレイピングなどで取得したリスト形式のデータは、tidyverse的にas_tibble()を使ってdata.frameに変換すると、扱いやすいです。
ですが、リストの要素にNULLが含まれていると、エラーがでます。

list_to_tibble.r

library(magrittr)
library(tibble)

data <- list(lm_id = "LMFA0000001", name = "2-methoxy-12-methyloctadec-17-en-5-ynoyl anhydride", main_class = "Other Fatty Acyls [FA00]", sub_class = NULL)
data

$lm_id
[1] "LMFA0000001"

$name
[1] "2-methoxy-12-methyloctadec-17-en-5-ynoyl anhydride"

$main_class
[1] "Other Fatty Acyls [FA00]"

$sub_class
NULL # <- NULLなのでエラーになる
list_to_tibble.r
data %>% as_tibble
Error: All columns in a tibble must be 1d or 2d objects:
* Column `sub_class` is NULL
Call `rlang::last_error()` to see a backtrace

リストに含まれるNULLをNAに置換する

NULL値があるといけないので、lapply()を使って、NULLをNAに置換してます。

list_to_tibble.r
data %<>% lapply(function(x) if(is.null(x)) {NA} else {x})
data
$lm_id
[1] "LMFA0000001"

$name
[1] "2-methoxy-12-methyloctadec-17-en-5-ynoyl anhydride"

$main_class
[1] "Other Fatty Acyls [FA00]"

$sub_class
[1] NA # NULLからNAに置換

NAにすれば、as_tibble()data.frameに変換できます。

list_to_tibble.r
data %<>% as_tibble
data
# A tibble: 1 x 4
  lm_id      name                                  main_class          sub_class
  <chr>      <chr>                                 <chr>               <lgl>
1 LMFA00000~ 2-methoxy-12-methyloctadec-17-en-5-y~ Other Fatty Acyls ~ NA
1
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
1
0