r - 如何根据查找表更改数据框列的属性
问题描述
我有一个包含很多列的数据框,我想编辑列的属性,以便每个列属性都基于查找表中的匹配值。
虚拟数据
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
我的问题
如何根据表中的匹配值编辑数据框中所有列的“标签”属性?(假设值的顺序不一定与 的顺序匹配)。df
label_dictionary
label_dictionary$variable
colnames(df)
谢谢!
解决方案
而不是as.table
,我建议使用setNames
:
label_dictionary <- read.csv("myfile.csv", stringsAsFactors=FALSE)
label_dictionary <- setNames(label_dictionary[,"label"], label_dictionary[,"variable"])
基本上,您将matrix
ordata.frame
对象转换为命名向量。然后你使用这个向量通过一个简单的查找来设置属性:
for (x in colnames(df)) attr(df[,x], "label") <- label_dictionary[x]
循环遍历所有列名并设置属性。
推荐阅读
- flutter - Flutter Firebase Sign In with Apple 未在 firebase auth 用户中返回电子邮件
- excel - 将格式信息编码到 Google 表格或 Excel 公式中
- python - 如何在无序列表 selenium + python 中抓取信息
- typescript - Typescript - 输出类型取决于输入类型
- android-room - 无法弄清楚如何使用 pojo 从一个 Room 实体构造 ViewPager2 的数据
- arrays - 索引匹配不同日期和值之间的搜索
- webrtc - 无法访问 coturn 网络管理员
- json - 如何从一个数据框中获取规则并将其应用于其他数据框以获取 python 中的统计信息?
- scheme - SICP Ex。1.17 - “快速乘法”比“乘法”慢?
- c# - 为什么我不能通过反射获得控件的 MouseDown 事件