我有一个包含 20 个变量的数据框。我需要使用 attr() 函数为某些变量分配描述。所需变量的描述和名称在另一个数据框中形成两列。我想使用 apply 函数来避免多次重复代码。
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"
我尝试了下面的代码,但我知道我应该对 y 做不同的事情。
cols <- label$variable
subset <- data %>% select(cols)
description <- label$description
lapply(data, function(x, y) {
attr(x[names(subset)], 'label') = y
}, description)
你能帮我吗?
这是一种使用
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"