首页 > 解决方案 > 如何根据查找表更改数据框列的属性

问题描述

我有一个包含很多列的数据框,我想编辑列的属性,以便每个列属性都基于查找表中的匹配值。

虚拟数据

df <- data.frame(id = c(1,2,3), age = c(10, 30, 55), eye_color = c("blue", "brown", "green"))

> df

#   id age eye_color
# 1  1  10      blue
# 2  2  30     brown
# 3  3  55     green

如果我只想更改单个 column 的属性df$id,我会这样做:

attr(df$id, "label") <- "Person's ID"

> attr(df$id, "label")
# [1] "Person's ID"

但是,我需要编辑所有列的“标签”属性,并且希望效率更高。所以我希望依靠一个单独的表来匹配列名和“标签”属性。(实际上,我会导入在 R 之外手动创建的 CSV 文件,但为了后期可重现性,这里有一个虚拟表来表达我的观点。它可能是一个数据框,因为对象类型无关紧要):

label_dictionary <-
  matrix(
    c(
      "id",
      "Person's ID",
      "age",
      "Person's age when taking the survey",
      "eye_color",
      "Person's eye color"
    ),
    ncol = 2,
    byrow = TRUE
  )
colnames(label_dictionary) <- c("variable", "label")
label_dictionary <- as.table(label_dictionary)

> label_dictionary

#   variable  label                              
# A id        Person's ID                        
# B age       Person's age when taking the survey
# C eye_color Person's eye color     

我的问题

如何根据表中的匹配值编辑数据框中所有列的“标签”属性?(假设值的顺序不一定与 的顺序匹配)。dflabel_dictionarylabel_dictionary$variable colnames(df)

谢谢!

标签: rdataframe

解决方案


而不是as.table,我建议使用setNames

label_dictionary <- read.csv("myfile.csv", stringsAsFactors=FALSE)
label_dictionary <- setNames(label_dictionary[,"label"], label_dictionary[,"variable"])

基本上,您将matrixordata.frame对象转换为命名向量。然后你使用这个向量通过一个简单的查找来设置属性:

for (x in colnames(df)) attr(df[,x], "label") <- label_dictionary[x]

循环遍历所有列名并设置属性。


推荐阅读