In R, how do you differentiate a result is vector

2020-02-07 07:10发布

I am learning R right now and using R Studio

I wrote :

library(datasets)
data(mtcars)

## split() function divides the data in a vector. unsplit() function do the reverse.
split(mtcars$mpg, mtcars$cyl)

I get back:

$`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

I know that split returns vector. But is this a vector of vectors of length 1?

Visually in R Studio, what is the difference in the display of vector and a matrix?

标签: r vector matrix
2条回答
家丑人穷心不美
2楼-- · 2020-02-07 07:45

There are a variety of is. functions one of which is

 is.matrix

You could simulate is.matrix with:

 is.it.a.matrix <- function(x) is.atomic(x) & length(dim(x)) == 2

The notion of a vector from general mathematical perspective and results from is.vector are not exactly in alignment. See this earlier response regarding is.vector. Lists, surprisingly to me anyway, are 'vectors' in R technical parlance. Notice that data.frames which do have a dim attribute are excluded from that category by not being atomic.

查看更多
Explosion°爆炸
3楼-- · 2020-02-07 08:02

Here are a few ways to see what the result of split(calculations..) is:

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))

You can also assing the a new object with the list and interrogate it using the previous functions

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 ...

By now, it's clear the object split returns is a list. In this case, the list cars_ls has 3 numeric vectors. You can index the list in a few ways. Here are some examples. Obviously, there is no matrix here.

# Using $[backquote][list name][back quote]
cars_ls$`4` 

# Including names using [
cars_ls[1]

# No names using [[
cars_ls[[1]]

EDIT Technically speaking, lists are vectors also. Here are a few more functions to check what type of object you have.

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

Regarding what unlist does:

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 is a numeric vector, clearly not a list. So unlist() grabs a list and unlists it.

You can find a more detailed description of these functions in the R Language Definition

查看更多
登录 后发表回答