-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 に答える