how to assign an attribute to some variables using another data frame?

54 views Asked by At

I have a data frame with 20 variables. I need to assign a description to some of the variables using the attr() function. The descriptions and the name of the desired variables form two columns in another data frame. I would like to use the apply function to avoid repeating the code several times.

data <- list(id = c("AA", "BB", "CC"), bodyPart = c("leg", "arm", "knee"),side = c("LEFT", "RIGHT", "LEFT"), device = c("LLI", "LSM", "GHT"), power = c("high", "low", "med") ) %>%  as.data.frame()
label <- list(variable = c("side", "power"), description = c("the laterality test", "the estimated power"))
attr(data$side, 'label') = "the laterality test"
attr(data$power, 'label') = "the estimated power"

I tried the code below but I know I should do differently about y.

cols <- label$variable
subset <- data %>% select(cols)
description <- label$description
lapply(data, function(x, y) {
  attr(x[names(subset)], 'label') = y
}, description)

Could you please help me?

3

There are 3 answers

0
Onyambu On BEST ANSWER

Other ways to do this:

data[label$variable] <- Map(structure, data[label$variable], label=label$description)

str(data)
'data.frame':   3 obs. of  5 variables:
 $ id      : chr  "AA" "BB" "CC"
 $ bodyPart: chr  "leg" "arm" "knee"
 $ side    : chr  "LEFT" "RIGHT" "LEFT"
  ..- attr(*, "label")= chr "the laterality test"
 $ device  : chr  "LLI" "LSM" "GHT"
 $ power   : chr  "high" "low" "med"
  ..- attr(*, "label")= chr "the estimated power"

data[label$variable] <- Map(`attr<-`, data[label$variable], 'label', label$description)
3
stefan On

Here is an approach using Map:

data[label$variable] <- Map(\(x, y) {
  attr(x, "label") <- y
  x
}, data[label$variable], label$description)

str(data)
#> 'data.frame':    3 obs. of  5 variables:
#>  $ id      : chr  "AA" "BB" "CC"
#>  $ bodyPart: chr  "leg" "arm" "knee"
#>  $ side    : chr  "LEFT" "RIGHT" "LEFT"
#>   ..- attr(*, "label")= chr "the laterality test"
#>  $ device  : chr  "LLI" "LSM" "GHT"
#>  $ power   : chr  "high" "low" "med"
#>   ..- attr(*, "label")= chr "the estimated power"
1
jay.sf On

Using `attr<-`().

> vars <- c('side', 'power')
> labs <- c("the laterality test", "the estimated power")
> data[vars] <- Map(`attr<-`, data[vars], 'label', labs)
> str(data)
'data.frame':   3 obs. of  5 variables:
 $ id      : chr  "AA" "BB" "CC"
 $ bodyPart: chr  "leg" "arm" "knee"
 $ side    : chr  "LEFT" "RIGHT" "LEFT"
  ..- attr(*, "label")= chr "the laterality test"
 $ device  : chr  "LLI" "LSM" "GHT"
 $ power   : chr  "high" "low" "med"
  ..- attr(*, "label")= chr "the estimated power"

Data:

> dput(data)
structure(list(id = c("AA", "BB", "CC"), bodyPart = c("leg", 
"arm", "knee"), side = c("LEFT", "RIGHT", "LEFT"), device = c("LLI", 
"LSM", "GHT"), power = c("high", "low", "med")), class = "data.frame", row.names = c(NA, 
-3L))