在R中的列表中获取数据帧的维度

时间:2014-12-06 20:25:20

标签: r

如果我有一个数据框列表(DF1,DF2,DF3 ......),其中每个数据框具有可变数量的行和列,那么,如何从列表中查看所有数据框的名称及其尺寸。 当我执行names(mylist)命令时,它只输出数据帧的名称,但我也想要它们各自的尺寸。我怎么能这样做?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以编写一个函数,然后通过列表调用它

f <- function(x) {
    list(dim = dim(x), names = names(x))
}
x <- list(mtcars = mtcars, iris = iris)

lapply(x, f)
# $mtcars
# $mtcars$dim
# [1] 32 11
# 
# $mtcars$names
# [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
# 
# 
# $iris
# $iris$dim
# [1] 150   5
# 
# $iris$names
# [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"    

如果你不喜欢,那就更容易了:

lapply(x, attributes)

# $mtcars
# $mtcars$names
# [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
# 
# $mtcars$row.names
# [1] "Mazda RX4"           "Mazda RX4 Wag"       "Datsun 710"          "Hornet 4 Drive"      "Hornet Sportabout"  
# [6] "Valiant"             "Duster 360"          "Merc 240D"           "Merc 230"            "Merc 280"           
# [11] "Merc 280C"           "Merc 450SE"          "Merc 450SL"          "Merc 450SLC"         "Cadillac Fleetwood" 
# [16] "Lincoln Continental" "Chrysler Imperial"   "Fiat 128"            "Honda Civic"         "Toyota Corolla"     
# [21] "Toyota Corona"       "Dodge Challenger"    "AMC Javelin"         "Camaro Z28"          "Pontiac Firebird"   
# [26] "Fiat X1-9"           "Porsche 914-2"       "Lotus Europa"        "Ford Pantera L"      "Ferrari Dino"       
# [31] "Maserati Bora"       "Volvo 142E"         
# 
# $mtcars$class
# [1] "data.frame"
# 
# 
# $iris
# $iris$names
# [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"     
# 
# $iris$row.names
# [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29
# [30]  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58
# [59]  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87
# [88]  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
# [117] 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
# [146] 146 147 148 149 150
# 
# $iris$class
# [1] "data.frame"