gpt4 book ai didi

r - 使用 dplyr::mutate() 修改任意列属性

转载 作者:行者123 更新时间:2023-12-01 22:55:47 25 4
gpt4 key购买 nike

我想修改 dplyr::mutate() 中的列属性。以下是一些示例数据:

library(dplyr, warn.conflicts = FALSE)
v1 <- tibble(
id = 1:5,
visit = 1,
x = 1:5,
y = c(0, 0, 0, 1, 1)
)

我想得到的最终结果与我从中得到的结果相同:

attr(v1$id, "source") <- "Collected at v1"
attr(v1$visit, "source") <- "Collected at v1"
attr(v1$x, "source") <- "Collected at v1"
attr(v1$y, "source") <- "Collected at v1"

我知道我可以只使用 for 循环。

for (col in names(v1)) {
attr(v1[[col]], "source") <- "Collected at v1"
}

但是,我有理由想在 dplyr 中执行此操作。我正在努力做到这一点。

v1 %>% 
mutate(
across(
.cols = everything(),
.fns = ~ function_to_update_attributes("source", "Collected at v1")
)
)

现在,我什至不能让它对单个变量起作用。这是我得到的最接近的结果。

v1 %>% 
mutate(
id = `<-`(attr(.[["id"]], "source"), "Collected at v1")
)

哪个返回

# A tibble: 5 × 4
id visit x y
<chr> <dbl> <int> <dbl>
1 Collected at v1 1 1 0
2 Collected at v1 1 2 0
3 Collected at v1 1 3 0
4 Collected at v1 1 4 1
5 Collected at v1 1 5 1

😞 欢迎并赞赏任何建设性反馈!

这也发布在 RStudio 社区上:https://community.rstudio.com/t/modify-arbitrary-column-attributes-using-dplyr-mutate/144502

最佳答案

我们可以使用 dplyr 直接在向量上应用属性

library(dplyr)
v1 <- v1 %>%
mutate(across(everything(),
~ {attr(.x, "source") <- "Collected at v1"
.x} ))

-输出

> str(v1)
tibble [5 × 4] (S3: tbl_df/tbl/data.frame)
$ id : int [1:5] 1 2 3 4 5
..- attr(*, "source")= chr "Collected at v1"
$ visit: num [1:5] 1 1 1 1 1
..- attr(*, "source")= chr "Collected at v1"
$ x : int [1:5] 1 2 3 4 5
..- attr(*, "source")= chr "Collected at v1"
$ y : num [1:5] 0 0 0 1 1
..- attr(*, "source")= chr "Collected at v1"

或者如果我们想使用访问列名使用cur_column()并分配 <<-

v1 %>%
mutate(across(everything(),
~ {attr(v1[[cur_column()]], "source") <<- "Collected at v1"
.x}))

-输出

> str(v1)
tibble [5 × 4] (S3: tbl_df/tbl/data.frame)
$ id : int [1:5] 1 2 3 4 5
..- attr(*, "source")= chr "Collected at v1"
$ visit: num [1:5] 1 1 1 1 1
..- attr(*, "source")= chr "Collected at v1"
$ x : int [1:5] 1 2 3 4 5
..- attr(*, "source")= chr "Collected at v1"
$ y : num [1:5] 0 0 0 1 1
..- attr(*, "source")= chr "Collected at v1"

或者如果我们想复制相同的行为,即使用原始数据对象名称及其列名称,如 for循环,使用 reduce

library(purrr)
v1 <- reduce(names(v1), ~ {
attr(.x[[.y]], "source") <- "Collected at v1"
.x}, .init = v1)

-输出

> str(v1)
tibble [5 × 4] (S3: tbl_df/tbl/data.frame)
$ id : int [1:5] 1 2 3 4 5
..- attr(*, "source")= chr "Collected at v1"
$ visit: num [1:5] 1 1 1 1 1
..- attr(*, "source")= chr "Collected at v1"
$ x : int [1:5] 1 2 3 4 5
..- attr(*, "source")= chr "Collected at v1"
$ y : num [1:5] 0 0 0 1 1
..- attr(*, "source")= chr "Collected at v1"

关于r - 使用 dplyr::mutate() 修改任意列属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73309648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com