Home > Net >  Modify arbitrary column attributes using dplyr::mutate()
Modify arbitrary column attributes using dplyr::mutate()

Time:08-11

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

  • Related