动态使用atter功能

发布于 2025-02-02 04:50:13 字数 617 浏览 3 评论 0原文

考虑到以下数据框架,

df<-data.frame(a=c(1,2,3))

我可以通过这样做来显示它:

df

或者

get("df")

,我可以通过执行此操作给予属性:

attr(df,"anyAttribute")<-"df attribute"
attributes(df)
$names
[1] "a"

$class
[1] "data.frame"

$row.names
[1] 1 2 3

$anyAttribute
[1] "df attribute"

有什么方法可以动态地赋予数据帧吗?我想要的就是这样:

> attr(get("df"),"anyAttribute")<-"df attribute"
Error in attr(get("df"), "anyAttribute") <- "df attribute" : 
  destino de la asignación se expande a un objeto fuera del lenguaje

Considering the following data frame

df<-data.frame(a=c(1,2,3))

I can show it by doing:

df

or

get("df")

Also, I can give an attribute to it by doing this:

attr(df,"anyAttribute")<-"df attribute"
attributes(df)
$names
[1] "a"

$class
[1] "data.frame"

$row.names
[1] 1 2 3

$anyAttribute
[1] "df attribute"

Is there any way to give attributes to dataframes dynamically?. What I want is something like this:

> attr(get("df"),"anyAttribute")<-"df attribute"
Error in attr(get("df"), "anyAttribute") <- "df attribute" : 
  destino de la asignación se expande a un objeto fuera del lenguaje

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浮光之海 2025-02-09 04:50:13

你的意思是吗?

r <- `attr<-`(get("df"), "anyAttribute", "df attribute")

attributes(r)
# $names
# [1] "a"
# 
# $class
# [1] "data.frame"
# 
# $row.names
# [1] 1 2 3
# 
# $anyAttribute
# [1] "df attribute"

Do you mean this?

r <- `attr<-`(get("df"), "anyAttribute", "df attribute")

attributes(r)
# $names
# [1] "a"
# 
# $class
# [1] "data.frame"
# 
# $row.names
# [1] 1 2 3
# 
# $anyAttribute
# [1] "df attribute"
两人的回忆 2025-02-09 04:50:13

我们可以使用分配更新原始对象

tmp <- get('df')
attr(tmp, 'anyAttribute') <- 'df attribute'
assign('df', tmp)

-Output

> str(df)
'data.frame':   3 obs. of  1 variable:
 $ a: num  1 2 3
 - attr(*, "anyAttribute")= chr "df attribute"

We can use assign to update the original object

tmp <- get('df')
attr(tmp, 'anyAttribute') <- 'df attribute'
assign('df', tmp)

-output

> str(df)
'data.frame':   3 obs. of  1 variable:
 $ a: num  1 2 3
 - attr(*, "anyAttribute")= chr "df attribute"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文