rapplyattr

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


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?


Solution

  • 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)