LoginSignup
3
2

More than 5 years have passed since last update.

素のRでdata.frameにlistを含める

Last updated at Posted at 2017-12-04

追記@2017/12/05

I()を使うと楽というかヘルプによると勝手に変換してほしくなければI()を使えということのようです。

入力
> data.frame(
+   x = I(list("a", TRUE, 0)),
+   y = 1:3
+ )
出力
     x y
1    a 1
2 TRUE 2
3    0 3

以下原文

最初そんなことできたっけと思ってしまったけど、できる。data.frameはlistなので。

入力
df <- data.frame(x = 1:3)
class(df)
typeof(df)
出力
> class(df)
[1] "data.frame"
> typeof(df)
[1] "list"

data.frameは列のlist、したがって要素としてlistを含めそうなものだがdata.frame()にlistを与えても展開されてしまう。

入力
data.frame(
  x = list("a", TRUE, 0),
  y = 1:3
  )
出力
  x..a. x.TRUE x.0 y
1     a   TRUE   0 1
2     a   TRUE   0 2
3     a   TRUE   0 3

しかし後から列にlistを与えることはできる。

入力
df$y = list(1, FALSE, mean)
df
出力
  x                                     y
1 1                                     1
2 2                                 FALSE
3 3 function (x, ...) , UseMethod("mean")

data.frameもlistなので、nested data.frameも作れる。

入力
df <- data.frame(x = 1:3)

df_list <- list(
  df_a = data.frame(l = rnorm(3)),
  df_b = data.frame(l = rnorm(3), m = rnorm(3)),
  df_c = data.frame(l = rnorm(3), m = rnorm(3), n = rnorm(3))
)

df$y <- df_list

str(df)
出力
'data.frame':   3 obs. of  2 variables:
 $ x: int  1 2 3
 $ y:List of 3
  ..$ df_a:'data.frame':    3 obs. of  1 variable:
  .. ..$ l: num  0.5879 0.0696 -0.8323
  ..$ df_b:'data.frame':    3 obs. of  2 variables:
  .. ..$ l: num  -0.723 1.752 -0.724
  .. ..$ m: num  0.98 0.833 -0.111
  ..$ df_c:'data.frame':    3 obs. of  3 variables:
  .. ..$ l: num  0.102 -0.264 1.623
  .. ..$ m: num  2.563 0.428 0.106
  .. ..$ n: num  2.086 0.249 -0.538

参照も普通に。

入力
df$y$df_a$l
出力
[1]  0.58786320  0.06962387 -0.83226396

listのlistなのでrapply()が活きるぞ。

入力
rapply(df, mean)
出力
          x    y.df_a.l    y.df_b.l    y.df_b.m    y.df_c.l    y.df_c.m 
 2.00000000 -0.05825896  0.10152878  0.56755911  0.48687462  1.03224899 
   y.df_c.n 
 0.59883656 
3
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
3
2