Modify arbitrary column attributes using dplyr::mutate()

I would like to modify column attributes inside of dplyr::mutate(). Here is some example data:

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

The end result I would like to get is the same result I would get from:

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"

I know I can just use a for loop.

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

However, I have reasons for wanting to do this inside of dplyr. I'm trying to get to something like this.

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

Right now, I can't even get this to work for a single variable. This is the closest I've gotten.

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

Which returns

# 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

:disappointed: Any constructive feedback is welcome and appreciated!

This is also posted on Stack Overflow at: r - Modify arbitrary column attributes using dplyr::mutate() - Stack Overflow

Have you looked at the below function?

magrittr::set_attr()

{magrittr} exports a load of stuff that lets you do things like this in pipelines.

2 Likes

Thank you, @JackDavison ! I knew there had to be a relatively simple solution.

So what actually would be the full dplyr code as a solution ?

Hi @Andrzej ,

In this case, the full solution would be

v1 <- tibble(
  id = 1:5,
  visit = 1,
  x = 1:5,
  y = c(0, 0, 0, 1, 1)
)

# One column
v1 <- v1 %>%
  mutate(id = magrittr::set_attr(id, "source", "Collected at v1"))

# All columns
v1 <- v1 %>%
  mutate(
    across(
      everything(), 
      ~ magrittr::set_attr(.x, "source", "Collected at v1")
    )
  )

Thank you very much indeed @brad.cannell .

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.