如何借助另一个数据框,用apply函数为R数据框变量分配attr属性?
为数据框变量批量添加属性标签
我有一个包含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"
我尝试的错误代码
cols <- label$variable subset <- data %>% select(cols) description <- label$description lapply(data, function(x, y) { attr(x[names(subset)], 'label') = y }, description)
解决方案
你的问题出在lapply的使用逻辑上:lapply遍历的是数据框的每一列,但你没有把变量名和描述信息对应起来,而且直接修改遍历出来的列不会同步到原数据框。
这里推荐两种简洁的实现方式:
方法1:用Map函数(配对处理元素)
Map可以同时遍历变量名和描述信息,直接修改原数据框的列属性:
# 先把label转成数据框更方便处理 label_df <- as.data.frame(label) # 用Map批量设置属性 Map(function(var, desc) { attr(data[[var]], "label") <- desc }, label_df$variable, label_df$description)
方法2:用purrr::walk2(tidyverse风格)
如果你习惯tidyverse工具,walk2适合这种需要执行副作用(修改属性)的操作:
library(purrr) walk2(label_df$variable, label_df$description, ~{ attr(data[[.x]], "label") <- .y })
验证结果
执行完后可以用以下代码检查属性是否设置成功:
# 查看单个变量的标签 attr(data$side, "label") attr(data$power, "label") # 查看所有变量的标签 sapply(data, function(x) attr(x, "label"))
内容的提问来源于stack exchange,提问作者Rara
相关产品推荐
相关产品推荐

