哪个数据类型最接近R

时间:2017-11-05 21:52:56

标签: r struct abstract-data-type

有什么方法可以在R中使用C结构,或者任何替代方案? 我正在搜索的是一种可以处理不同类型数据的数据类型,并以可理解的方式授予访问权限。 R列表已经执行此操作,但内容的访问是通过索引[[ ]]进行的。处理它似乎很麻烦,因为我必须记住第一个元素,秒等的确切内容.c结构是很好的例子,因为内容是用.运算符访问的,而程序员没有&# 39; t必须考虑[[nth]]保存的内容。

例如:

struct MyStuct{
    int powerLevel;
    int size;
} //create the data type

struct Mystruct variable;  //instantiate the object
variable.size  //access the content of the object

所以,我想要的是一种数据类型,用于存储时间序列的点,其SSE,组,K用于K均值,以及单个变量中的其他内容。我认为最接近的是C结构。

3 个答案:

答案 0 :(得分:3)

> n = c(2, 3, 5) 
> s = c("aa", "bb", "cc") 
> b = c(TRUE, FALSE, TRUE) 
> df = data.frame(n, s, b) 

数据框可以存储矢量。

答案 1 :(得分:2)

您可能希望查看使用R :: setClass

本质上,这允许您创建类定义并返回生成器函数以从类创建对象。就个人而言,我发现它在您描述的上下文中非常有用。要取消引用结构组件,您可以使用@,使用下面的示例CStructure@powerLevel将返回5

作为替代方案,可以考虑使用数据框,但是,数据框方法不会创建独立的类模板。它还要求所有条目的长度相同。数据框 对称 ,您的数据可能不是。

请参阅示例错误参考:数据框必须是对称的,详细信息请参见使用setClass的示例。这说两者都是选择。

我希望这个例子对你有用。

实施例

setClass(
  "CStruct",
  slots = list(
    powerLevel = "numeric",
    size = "numeric"
  )
)

CStructure <- new("CStruct", powerLevel =5, size=10)
CStructure
str(CStructure)
CStructure@powerLevel
CStructure@size

输出:

> setClass(
+   "CStruct",
+   slots = list(
+     powerLevel = "numeric",
+     size = "numeric"
+   )
+ )
> 
> CStructure <- new("CStruct", powerLevel =5, size=10)
> CStructure
An object of class "CStruct"
Slot "powerLevel":
[1] 5

Slot "size":
[1] 10

> str(CStructure)
Formal class 'CStruct' [package ".GlobalEnv"] with 2 slots
  ..@ powerLevel: num 5
  ..@ size      : num 10
> CStructure@powerLevel
[1] 5
> CStructure@size
[1] 10
> 

数据帧必须是对称的

> n = c(2, 3, 5)
> s = c("aa", "bb")
> b = c(TRUE, FALSE, TRUE)
> df = data.frame(n, s, b)
Error in data.frame(n, s, b) : 
  arguments imply differing number of rows: 3, 2

CStruct Alternative

setClass(
  "CStruct2",
  slots = list(
   n = "numeric",
   s = "character",
   b = "logical"
  )
)

CStructure2 <- new("CStruct2", n = c(2, 3, 5), 
                  s = c("aa", "bb"), 
                  b = c(TRUE, FALSE, TRUE) )
str(CStructure2)
CStructure2@n
CStructure2@s
CStructure2@b

输出:

> setClass(
+   "CStruct2",
+   slots = list(
+    n = "numeric",
+    s = "character",
+    b = "logical"
+   )
+ )
> 
> CStructure2 <- new("CStruct2", n = c(2, 3, 5), 
+                   s = c("aa", "bb"), 
+                   b = c(TRUE, FALSE, TRUE) )
> str(CStructure2)
Formal class 'CStruct2' [package ".GlobalEnv"] with 3 slots
  ..@ n: num [1:3] 2 3 5
  ..@ s: chr [1:2] "aa" "bb"
  ..@ b: logi [1:3] TRUE FALSE TRUE    
> CStructure2@n

[1] 2 3 5
> CStructure2@s
[1] "aa" "bb"
> CStructure2@b
[1]  TRUE FALSE  TRUE

答案 2 :(得分:1)

用点(。)访问的C结构

struct MyStruct{
    int powerLevel;
    int size;
} variable;  
variable.size; 

使用禁止的S($)访问类似的R代码

variable = list(
     powerlevel = 0,
     size = 0
)
variable$size