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?
Other ways to do this: