R:变量的类型和类 [英] R: Types and classes of variables

查看:137
本文介绍了R:变量的类型和类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个R问题:


  1. 类型之间有什么区别? typeof )和类(由 class 返回)?

  2. 什么是可能的变量类型和类?


<在R中,每个对象都有一个模式。前者表示对象如何存储在内存中(数字,字符,列表和函数),而后者表示它的抽象类型。例如:

  d < -  data.frame(V1 = c(1,2))
class d)
#[1]data.frame
mode(d)
#[1]list
typeof(d)
#list

正如你可以看到,数据框存储在内存中 list ,但它们被包装到 data.frame 对象中。后者允许使用成员函数以及重载函数,例如具有自定义行为的 print



typeof storage.mode )通常会与模式相同的信息,但不总是。例如:

  typeof(c(1,2))
#[1]double
mode(c(1,2))
#[1]numeric

此背后的原因可以在这里找到


R特定函数 typeof 返回R对象的类型



函数 mode 提供有关Becker,Chambers& Wilks(1988),并且与S语言的其他实现更兼容


我在上面发布的链接还包含一个列表所有本机R 基本类型(向量,列表等)和所有复合对象(factors和data.frames)以及如何模式 typeof 每种类型都相关。


Two R questions:

  1. What is the difference between the type (returned by typeof) and the class (returned by class) of a variable? Is the difference similar to that in, say, C++ language?
  2. What are possible types and classes of variables?

解决方案

In R every "object" has a mode and a class. The former represents how an object is stored in memory (numeric, character, list and function) while the later represents its abstract type. For example:

d <- data.frame(V1=c(1,2))
class(d)
# [1] "data.frame"
mode(d)
# [1] "list"
typeof(d)
# list

As you can see data frames are stored in memory as list but they are wrapped into data.frame objects. The latter allows for usage of member functions as well as overloading functions such as print with a custom behavior.

typeof(storage.mode) will usually give the same information as mode but not always. Case in point:

typeof(c(1,2))
# [1] "double"
mode(c(1,2))
# [1] "numeric"

The reasoning behind this can be found here:

The R specific function typeof returns the type of an R object

Function mode gives information about the mode of an object in the sense of Becker, Chambers & Wilks (1988), and is more compatible with other implementations of the S language

The link that I posted above also contains a list of all native R basic types (vectors, lists etc.) and all compound objects (factors and data.frames) as well as some examples of how mode, typeof and class are related for each type.

这篇关于R:变量的类型和类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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