为什么此数据框变量采用未明确分配给它的属性? (dplyr-R)
Why does this dataframe variable take an attribute not explicity assigned to it? (dplyr-R)
好奇:有人可以解释为什么 df1 和 df3 最终被分配了相同的属性,即使 df3 是明确修改的属性吗?我会假设因为 df1 和 df3 有不同的内存地址,所以它们不会同时被修改。管道问题?--对象如何绑定在一起?
library(lobstr)
library(dplyr)
library(data.table)
df1 <- data.frame(x = 1:3, y = letters[1:3])
df2<-data.frame(df1)
df3<-df2%>% dplyr::mutate_at(vars(ends_with("x")),
funs(data.table::setattr(.,"label","An x column")))
str(df1)
str(df3)
obj_addr(df1)
obj_addr(df3)
结果
str(df1)
'data.frame': 3 obs. of 2 variables:
$ x: int 1 2 3
..- attr(*, "label")= chr "An x column"
$ y: Factor w/ 3 levels "a","b","c": 1 2 3
str(df3)
'data.frame': 3 obs. of 2 variables:
$ x: int 1 2 3
..- attr(*, "label")= chr "An x column"
$ y: Factor w/ 3 levels "a","b","c": 1 2 3
obj_addr(df1)
[1] "0xafe6a98"
obj_addr(df3)
[1] "0x98deef0"
根据 setattr
的文档:
In data.table, all set* functions change their input by reference.
That is, no copy is made at all, other than temporary working memory
which is as large as one column. The only other data.table operator
that modifies input by reference is :=. Check out the See Also section
below for other set* function that data.table provides.
如果您想使用正常的修改时复制语义指定属性,您可以使用 structure
:
df3 <- df2 %>%
dplyr::mutate_at(vars(ends_with("x")), funs(structure(., label = "An x column")))
好奇:有人可以解释为什么 df1 和 df3 最终被分配了相同的属性,即使 df3 是明确修改的属性吗?我会假设因为 df1 和 df3 有不同的内存地址,所以它们不会同时被修改。管道问题?--对象如何绑定在一起?
library(lobstr)
library(dplyr)
library(data.table)
df1 <- data.frame(x = 1:3, y = letters[1:3])
df2<-data.frame(df1)
df3<-df2%>% dplyr::mutate_at(vars(ends_with("x")),
funs(data.table::setattr(.,"label","An x column")))
str(df1)
str(df3)
obj_addr(df1)
obj_addr(df3)
结果
str(df1)
'data.frame': 3 obs. of 2 variables:
$ x: int 1 2 3
..- attr(*, "label")= chr "An x column"
$ y: Factor w/ 3 levels "a","b","c": 1 2 3
str(df3)
'data.frame': 3 obs. of 2 variables:
$ x: int 1 2 3
..- attr(*, "label")= chr "An x column"
$ y: Factor w/ 3 levels "a","b","c": 1 2 3
obj_addr(df1)
[1] "0xafe6a98"
obj_addr(df3)
[1] "0x98deef0"
根据 setattr
的文档:
In data.table, all set* functions change their input by reference. That is, no copy is made at all, other than temporary working memory which is as large as one column. The only other data.table operator that modifies input by reference is :=. Check out the See Also section below for other set* function that data.table provides.
如果您想使用正常的修改时复制语义指定属性,您可以使用 structure
:
df3 <- df2 %>%
dplyr::mutate_at(vars(ends_with("x")), funs(structure(., label = "An x column")))