Produce a graphic tree diagram showing the structure of an R object

試著忘記壹切 提交于 2021-02-08 09:27:09

问题


In R, str() is handy for showing the structure of an object, such as the list of lists returned by lm() and other modelling functions, but it gives way too much output. I'm looking for some tool to create a simple tree diagram showing only the names of the list elements and their structure.

e.g., for this example,

data(Prestige, package="car")
out <- lm(prestige ~ income+education+women, data=Prestige)
str(out, max.level=2)
#> List of 12
#>  $ coefficients : Named num [1:4] -6.79433 0.00131 4.18664 -0.00891
#>   ..- attr(*, "names")= chr [1:4] "(Intercept)" "income" "education" "women"
#>  $ residuals    : Named num [1:102] 4.58 -9.39 4.69 4.22 8.15 ...
#>   ..- attr(*, "names")= chr [1:102] "gov.administrators" "general.managers" "accountants" "purchasing.officers" ...
#>  $ effects      : Named num [1:102] -472.99 -123.61 -92.61 -2.3 6.83 ...
#>   ..- attr(*, "names")= chr [1:102] "(Intercept)" "income" "education" "women" ...
#>  $ rank         : int 4
#>  $ fitted.values: Named num [1:102] 64.2 78.5 58.7 52.6 65.3 ...
#>   ..- attr(*, "names")= chr [1:102] "gov.administrators" "general.managers" "accountants" "purchasing.officers" ...
#>  $ assign       : int [1:4] 0 1 2 3
#>  $ qr           :List of 5
#>   ..$ qr   : num [1:102, 1:4] -10.1 0.099 0.099 0.099 0.099 ...
#>   .. ..- attr(*, "dimnames")=List of 2
#>   .. ..- attr(*, "assign")= int [1:4] 0 1 2 3
#>   ..$ qraux: num [1:4] 1.1 1.44 1.06 1.06
#>   ..$ pivot: int [1:4] 1 2 3 4
#>   ..$ tol  : num 1e-07
#>   ..$ rank : int 4
#>   ..- attr(*, "class")= chr "qr"
#>  $ df.residual  : int 98
...

I would like to get something like this:

This is similar to what I get from tree for file folders in my file system:

C:\Dropbox\Documents\images>tree
Folder PATH listing
Volume serial number is 2250-8E6F
C:.
+---cartoons
+---chevaliers
+---icons
+---milestones
+---minard
    +---minard-besancon

The result could be either in graphic characters, as in tree or an actual graphic as shown above. Is anything like this available?


回答1:


A simple approach to getting this from the str output would be something like...

a <- capture.output(str(out, max.level=2))
a <- trimws(gsub("\\:.*", "", a[grepl("\\$", a)]))
cat(a, sep="\n")

$ coefficients
$ residuals
$ effects
$ rank
$ fitted.values
$ assign
$ qr
..$ qr
..$ qraux
..$ pivot
..$ tol
..$ rank
$ df.residual
$ xlevels
$ call
$ terms
$ model
..$ prestige
..$ income
..$ education
..$ women


来源:https://stackoverflow.com/questions/46606538/produce-a-graphic-tree-diagram-showing-the-structure-of-an-r-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!