有没有更简单的方法来访问R中的类的属性,我可以使用点表示法吗? [英] Is there an easier way to access attributes of a class in R, can I use dot notation?

查看:78
本文介绍了有没有更简单的方法来访问R中的类的属性,我可以使用点表示法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中创建了一个包含几个属性的对象.如何轻松访问它们?

I have created an object in R that contains several attributes. How can I easily access them?

我可以做到:

attr(x, attributeName)

或:

attributes(x)$attributeName

但是它们都不是很方便.

but none of them is really convenient.

有没有更快的方法(例如C ++或Java中的点)?

Is there a quicker way (like the dot in C++ or Java)?

推荐答案

不要为您的对象使用属性,请使用列表:

Don't use attributes for your object, use a list:

myobj <- structure(list(a = 1, b = 2), class = "myclass")
print.myclass <- function(x, ...) cat("A: ", x$a, " B: ", x$b, "\n", sep = "")
myobj

当然,如果要扩展现有对象(例如,矢量),则此方法可能不起作用,但以我的经验,这通常是构建对象的更好方法.

Of course, this might not work if you're extending an existing object (e.g. vector), but in my experience it's a generally better way to build objects.

这篇关于有没有更简单的方法来访问R中的类的属性,我可以使用点表示法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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