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

查看:1094
本文介绍了在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返回vector.但这是长度为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

关于取消列表的作用:

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天全站免登陆