我一直在努力研究如何在保持原始结构的情况下将表转换为 Dataframe 。
这就是我所说的表:
sample_size <- structure(c(0L, 2L, 2L, 0L, 3L, 1L, 3L, 9L, 13L, 0L, 0L, 0L,
0L, 1L, 0L, 0L, 0L, 0L, 1L, 2L, 0L, 0L, 2L, 0L, 0L, 0L, 0L, 0L,
2L, 0L, 0L, 2L, 0L, 0L, 0L, 0L, 0L, 6L, 0L, 9L, 2L, 0L, 0L, 1L,
0L, 0L, 8L, 0L, 6L, 1L, 0L, 0L, 2L, 1L, 3L, 16L, 10L, 0L, 2L,
0L, 0L, 6L, 33L, 4L, 30L, 18L, 3L, 0L, 14L, 1L, 12L, 40L, 1L,
13L, 9L, 0L, 0L, 0L, 0L, 11L, 25L, 1L, 5L, 2L, 0L, 2L, 0L, 0L,
1L, 16L, 2L, 17L, 1L, 0L, 2L, 0L, 0L, 2L, 19L, 2L, 3L, 1L, 0L,
1L, 0L, 3L, 4L, 17L, 0L, 2L, 0L, 0L, 2L, 0L, 0L, 0L, 0L, 0L,
2L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 2L, 0L, 0L, 2L, 0L, 0L, 0L,
0L, 1L, 1L, 0L, 0L, 2L, 0L, 2L, 4L, 1L, 0L, 2L, 0L, 0L, 2L, 0L,
3L, 7L, 2L, 4L, 10L, 16L, 4L, 2L, 0L, 22L, 11L, 31L, 7L, 8L,
18L, 3L, 3L, 1L, 21L, 8L, 31L, 4L, 10L, 11L, 3L, 2L, 0L, 19L,
5L, 29L, 4L, 6L, 16L, 2L, 1L, 2L, 11L, 12L, 27L, 6L, 7L, 14L,
2L, 0L, 2L, 14L, 9L, 35L), dim = c(9L, 11L, 2L), dimnames = structure(list(
c("Ardipithecus ramidus", "Australopithecus afarensis", "Australopithecus africanus",
"Australopithecus anamensis", "Early Homo", "Homo erectus",
"Homo habilis", "Paranthropus boisei", "Paranthropus robustus"
), c("C", "dc", "dm1", "dm2", "I1", "I2", "M1", "M2", "M3",
"P3", "P4"), c("L", "U")), names = c("", "", "")), class = "table")
当我看到对象sample_size
时,它看起来像这样:
, , = L
C dc dm1 dm2 I1 I2 M1 M2 M3 P3 P4
Ardipithecus ramidus 0 0 1 0 0 0 3 4 1 1 2
Australopithecus afarensis 2 0 2 2 6 8 16 30 13 5 17
Australopithecus africanus 2 0 0 0 0 0 10 18 9 2 1
Australopithecus anamensis 0 0 0 0 9 6 0 3 0 0 0
Early Homo 3 1 2 2 2 1 2 0 0 2 2
Homo erectus 1 0 0 0 0 0 0 14 0 0 0
Homo habilis 3 0 0 0 0 0 0 1 0 0 0
Paranthropus boisei 9 0 0 0 1 2 6 12 11 1 2
Paranthropus robustus 13 0 0 0 0 1 33 40 25 16 19
, , = U
C dc dm1 dm2 I1 I2 M1 M2 M3 P3 P4
Ardipithecus ramidus 2 0 0 0 1 0 4 7 4 4 6
Australopithecus afarensis 3 2 2 2 1 2 10 8 10 6 7
Australopithecus africanus 1 0 0 0 0 0 16 18 11 16 14
Australopithecus anamensis 0 0 0 0 0 0 4 3 3 2 2
Early Homo 1 2 1 2 2 2 2 3 2 1 0
Homo erectus 0 0 0 0 0 0 0 1 0 2 2
Homo habilis 3 0 0 0 2 3 22 21 19 11 14
Paranthropus boisei 4 0 0 0 4 7 11 8 5 12 9
Paranthropus robustus 17 0 0 0 1 2 31 31 29 27 35
但是,当我将sample_size
转换为 Dataframe 时,它改变了结构。
sample_size_df <- as.data.frame(sample_size)
head(sample_size_df)
Var1 Var2 Var3 Freq
1 Ardipithecus ramidus C L 0
2 Australopithecus afarensis C L 2
3 Australopithecus africanus C L 2
4 Australopithecus anamensis C L 0
5 Early Homo C L 3
6 Homo erectus C L 1
我如何通过保持表中显示的原始结构将原始表转换为 Dataframe ?
2条答案
按热度按时间ioekq8ef1#
当原始对象继承自
"table"
时,R的S3调度倾向于执行该转换;我们可以通过指定as.data.frame.matrix
来强制转换,因为这是假设二维的(您的数据为3),我们需要对每个平面执行此操作(使用apply
和它的MARGIN=3
)和rbind
。不过,我们需要小心,因为行名称在每个平面中都是重复的,所以我们将它们放到“真实的”列中,然后添加一列,这样您就可以知道数据来自哪个平面。这是一种混合基础/tibble/dplyr方法,有许多方法可以影响每个步骤:
如果你只想保留它的低音R,那么就稍微不那么优雅了:
(因为我使用
args=_
和base R的|>
原生管道,所以这需要R〉= 4.2.0;如果您有一个较低版本,那么您可以切换到magrittr::%>%
及其代名词.
,或者我们可以采取进一步的步骤来减轻,lmk。)bf1o4zei2#
或者,您可以使用展平的数组并将其重新整形为宽格式:
或者以
reshape()
为基础(名称需要稍微清理一下):