我现在正在学习R并使用R Studio
我写道:
library(datasets)
data(mtcars)
## split() function divides the data in a vector. unsplit() function do the reverse.
split(mtcars$mpg, mtcars$cyl)
我回来了:
$`4`
[1] 22.8 24.4 22.8 32.4 30.4 33.9 21.5 27.3 26.0 30.4 21.4
$`6`
[1] 21.0 21.0 21.4 18.1 19.2 17.8 19.7
$`8`
[1] 18.7 14.3 16.4 17.3 15.2 10.4 10.4 14.7 15.5 15.2 13.3 19.2 15.8 15.0
我知道split会返回vector。但这是一个长度为1的载体矢量吗?
在R Studio中可视化,向量和矩阵的显示有什么不同?
答案 0 :(得分:1)
以下是查看split(calculations..)
结果的几种方法:
class(split(mtcars$mpg, mtcars$cyl))
typeof(split(mtcars$mpg, mtcars$cyl))
mode(split(mtcars$mpg, mtcars$cyl))
storage.mode(split(mtcars$mpg, mtcars$cyl))
# str() Shows the structure of the object. It gives an small summary of it.
str(split(mtcars$mpg, mtcars$cyl))
您还可以使用列表协助新对象,并使用之前的函数
对其进行查询cars_ls <- split(mtcars$mpg, mtcars$cyl)
class(cars_ls)
typeof(cars_ls)
mode(cars_ls)
# and
str(cars_ls)
# List of 3
# $ 4: num [1:11] 22.8 24.4 22.8 32.4 30.4 33.9 21.5 27.3 26 30.4 ...0
# $ 6: num [1:7] 21 21 21.4 18.1 19.2 17.8 19.7
# $ 8: num [1:14] 18.7 14.3 16.4 17.3 15.2 10.4 10.4 14.7 15.5 15.2 ...
到目前为止,很明显对象拆分返回是一个列表。在这种情况下,列表cars_ls
有3个数字向量。
您可以通过几种方式索引列表。这里有些例子。显然,这里没有矩阵。
# Using $[backquote][list name][back quote]
cars_ls$`4`
# Including names using [
cars_ls[1]
# No names using [[
cars_ls[[1]]
修改强> 从技术上讲,列表也是矢量。这里有一些函数来检查你有什么类型的对象。
is.vector(cars_ls)
# [1] TRUE
is.matrix(cars_ls)
# [1] FALSE
is.list(cars_ls)
# [1] TRUE
is.data.frame(cars_ls)
# [1] FALSE
关于unlist的作用:
un_ls <- unlist(cars_ls)
mode(un_ls)
storage.mode(un_ls)
typeof(un_ls)
class(un_ls)
is.vector(un_ls)
# [1] TRUE
is.list(un_ls)
# [1] FALSE
un_ls
是一个数字向量,显然不是列表。所以unlist()
抓取一个列表并将其列入其中。
答案 1 :(得分:1)
有多种is.
函数,其中一个是
is.matrix
你可以用:
来模拟is.matrix is.it.a.matrix <- function(x) is.atomic(x) & length(dim(x)) == 2
来自一般数学视角的矢量概念和is.vector
的结果并不完全一致。无论如何,看到这个earlier response regarding is.vector
.列表,令我惊讶的是,R技术用语中的“向量”。请注意,具有dim属性的data.frames不是原子的,而是从该类别中排除的。