-1

我想在 data.frame 顶部存储其他信息并从函数中返回它。如您所见 - 附加数据消失。例子 :

> d<-data.frame(N1=c(1,2,3),N2=(LETTERS[1:3]))
> d
  N1 N2
1  1  A
2  2  B
3  3  C
> d.x = 3
> d
  N1 N2
1  1  A
2  2  B
3  3  C
> d.x
[1] 3
> foo1 <- function() {
+ d<-data.frame(N1=c(1,2,3),N2=(LETTERS[1:3]))
+ d.x=3
+ return(d)
+ }
> 
> d1<-foo1()
> d1
  N1 N2
1  1  A
2  2  B
3  3  C
> d1.x
Error: object 'd1.x' not found

我调查了assign,但由于 data.frame 是在函数内部创建并被返回的,所以我认为它在这里不相关。谢谢。

4

2 回答 2

1

您的评论建议您要创建一个名为“d.3”的属性(将“元数据”附加到 R 中的对象的常用方法)并使用 foo1 为数据框设置该属性:

d <- data.frame(N1=c(1,2,3),N2=(LETTERS[1:3]))
foo1 <- function(d, attrib) {
   attr(d, "d.x") <- attrib
  return(d)
  }
d <- foo1(d, 3)  # need to assign value to 'd' since function results are not "global"
d    # note that the default print method for dataframes does not show the attributes
#---------
  N1 N2
1  1  A
2  2  B
3  3  C
#-----
 attributes(d)
#-----

$names
[1] "N1" "N2"

$row.names
[1] 1 2 3

$class
[1] "data.frame"

$d.x
[1] 3

请参阅?attr?attributes了解更多详情。还有一个comments功能。

于 2013-02-13T21:16:17.960 回答
0

改变这个:

d.x=3

对此:

d$x=3
于 2013-02-13T19:50:21.810 回答