在 R 中,如何区分结果是向量还是矩阵? [英] In R, how do you differentiate a result is vector or matrix?

查看:29
本文介绍了在 R 中,如何区分结果是向量还是矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在学习 R 并使用 R Studio

I am learning R right now and using 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 返回向量.但这是长度为 1 的向量的向量吗?

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

视觉上在R Studio中,向量和矩阵的显示有什么区别?

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

推荐答案

这里有几种方法可以查看 split(calculations..) 的结果:

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

到目前为止,很明显,拆分返回的对象是一个列表.在这种情况下,列表 cars_ls 有 3 个数字向量.您可以通过几种方式为列表编制索引.这里有些例子.显然,这里没有矩阵.

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

关于 unlist 的作用:

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 是一个数值向量,显然不是一个列表.所以 unlist() 获取一个列表并将其取消列出.

un_ls is a numeric vector, clearly not a list. So unlist() grabs a list and unlists it.

您可以在 R 语言中找到这些函数的更详细说明定义

这篇关于在 R 中,如何区分结果是向量还是矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆