R datamembers and Attributes

别来无恙 提交于 2019-12-11 04:19:56

问题


I am very new to R and am not sure about the proper language when referring to datamembers and attributes of an object. I have an object-oriented programming language background in Java so I am probably referring to datamembers/attributes in a Java set of mind. Anyway, suppose I have a matrix matClust1 and I have done the following:

ids = vector()
for(i in 1:size)              #size is the number of rows in matClust1
{
  ids = c(ids, "exp")
}

attr(matClust1, "clustID") <- ids

I think of the above as setting an attribute/datamember of each row vector in matClust1 to "exp". This is because ids is created to have as many entries as there are rows in matClust1. So, I would like to be able to access this attribute/datamember by code like the following:

matClust1.clustID[2]            #get the clustID of row vector in matClust1

Apparently the . operator does not do this nor does the $ operator.

  1. How can I achieve this functionality in R?

EDIT: I already have the attribute set for rownames and what I am really looking for is another variable to work like rownames.


回答1:


You probably want a data.frame or data.table instead.

E.g.

df = data.frame(matClust1)

# create a new column and assign whatever to it:
df$clustID = "exp"

# use it however you like
df$someOtherColumn = paste(1:dim(df)[1], df$clustID)


来源:https://stackoverflow.com/questions/16022680/r-datamembers-and-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!