我对 R 还是很陌生,最近遇到了一些我不确定它是什么意思的东西。 data.frame
和 data.table
有相同的类型吗?一个对象可以有多种类型吗?将“汽车”从 data.frame
转换为 data.table
后,我显然无法应用适用于 data.frames
的函数,而不是data.table
,但 class()
显示“汽车”仍然是一个 data.frame
。有人知道为什么吗?
> class(cars)
[1] "data.frame"
> cars<-data.table(cars)
> class(cars)
[1] "data.table" "data.frame"
最佳答案
不清楚你所说的“我显然不能应用适用于 data.frames 而不是 data.table 的函数”是什么意思。
许多函数都可以按照您的预期工作,无论是应用于 data.frame
还是应用于 data.table
。特别是,如果您阅读 ?data.table
的帮助页面,您会在描述的第一段中找到这一特定行:
Since a
data.table
is adata.frame
, it is compatible with R functions and packages thatonly
acceptdata.frame
.
你可以自己测试一下:
library(data.table)
CARS <- data.table(cars)
以下都应该给你相同的结果。它们不是“data.table”做事的方式,但我只是突然想到了一些事情来向您展示许多(大多数?)函数可以与 data 一起使用。 table
与使用它们的方式相同提供)。
with(cars, tapply(dist, speed, FUN = mean))
with(CARS, tapply(dist, speed, FUN = mean))
aggregate(dist ~ speed, cars, as.vector)
aggregate(dist ~ speed, CARS, as.vector)
colSums(cars)
colSums(CARS)
as.matrix(cars)
as.matrix(CARS)
t(cars)
t(CARS)
table(cut(cars$speed, breaks=3), cut(cars$dist, breaks=5))
table(cut(CARS$speed, breaks=3), cut(CARS$dist, breaks=5))
cars[cars$speed == 4, ]
CARS[CARS$speed == 4, ]
但是,在某些情况下这不起作用。比较:
cars[cars$speed == 4, 1]
CARS[CARS$speed == 4, 1]
为了更好地理解这一点,我建议阅读常见问题解答。特别是,在这个问题上总结了几个相关点:what you can do with data.frame that you can't in data.table .
如果您的问题更笼统地说是“一个对象可以有多个类吗?”,那么您已经从自己的探索中看到,是的,它可以。有关更多信息,您可以阅读 this page from Hadley's devtools wiki .
类还会影响诸如对象如何打印以及它们如何与其他函数交互等事情。
考虑 rle
函数。如果你看class
,它返回“rle”,如果你看它的str
ucture,它表明它是一个列表。
> x <- rev(rep(6:10, 1:5))
> y <- rle(x)
> x
[1] 10 10 10 10 10 9 9 9 9 8 8 8 7 7 6
> y
Run Length Encoding
lengths: int [1:5] 5 4 3 2 1
values : int [1:5] 10 9 8 7 6
> class(y)
[1] "rle"
> str(y)
List of 2
$ lengths: int [1:5] 5 4 3 2 1
$ values : int [1:5] 10 9 8 7 6
- attr(*, "class")= chr "rle"
由于每个列表项的长度相同,您可能希望可以方便地使用 data.frame()
将其转换为 data.frame
。让我们试试吧:
> data.frame(y)
Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) :
cannot coerce class ""rle"" to a data.frame
> unclass(y)
$lengths
[1] 5 4 3 2 1
$values
[1] 10 9 8 7 6
> data.frame(unclass(y))
lengths values
1 5 10
2 4 9
3 3 8
4 2 7
5 1 6
或者,让我们向对象添加另一个 class
并尝试:
> class(y) <- c(class(y), "list")
> y ## Printing is not affected
Run Length Encoding
lengths: int [1:5] 5 4 3 2 1
values : int [1:5] 10 9 8 7 6
> data.frame(y) ## But interaction with other functions is
lengths values
1 5 10
2 4 9
3 3 8
4 2 7
5 1 6
关于data.frame 和 data.table 的 R 对象具有相同的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15984618/