[英]r data.frame with a list
我有一個data.frame(從jsonlite :: fromJSON中讀取),其中包含一些data.frame列表,例如:
# > str(dat)
# 'data.frame': 2 obs. of 3 variables:
# $ id : int 1 2
# $ name : chr "Julie" "Justin"
# $ score :List of 2
# ..$ : NULL
# ..$ :'data.frame': 5 obs. of 2 variables:
# .. ..$ rid : int 1 2 3 4 5
# .. ..$ math : int 5 17 19 12 16
我想將數據轉換為以下形式:
# id name score.rid score.math
# 1 Julie NA NA
# 2 Justin 1 5
# 2 Justin 2 17
# 2 Justin 3 19
# 2 Justin 4 12
# 2 Justin 5 16
對於NULL
score
值,使用purrr
map
將其更改為NA
,然后轉換為tibble
和unnest
library(dplyr)
library(purrr)
library(tidyr)
dat %>%
mutate(score = map(score, ~ if(is.null(.x)) tibble(NA) else as_tibble(.x))) %>%
unnest %>%
select(-`NA`)
# id name rid math
#1 1 Julie NA NA
#2 2 Justin 1 5
#3 2 Justin 2 17
#4 2 Justin 3 19
#5 2 Justin 4 12
#6 2 Justin 5 16
dat <- data.frame(id = 1:2, name = c("Julie", "Justin"),
score = I(list(NULL, data.frame(rid = 1:5,
math = c(5, 17, 19, 12, 16)))), stringsAsFactors = FALSE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.