[英]How to use variable labels in an R data frame
我正在嘗試分配然后使用變量標簽,然后將我的工作交給一個熟悉 SPSS 的新手 R 程序員。 當其他程序員使用數據時,她會想要制作表格。 她可能不記得 h1 是什么,但會知道“以英尺為單位的高度”是什么。
我已經分配了標簽。 現在我該如何使用它們?
澄清:一旦我有了標簽,我想像使用列名一樣使用標簽。 因此,在 RStudio 中,如果我輸入“heights$”,我希望看到“高度以英尺為單位”作為選項。 但我不想丟失列名。
library(Hmisc) # variable labels
heights = data.frame(h1 = c(4,5,6, 4), h2 = c(48, 60, 72, 48))
label(heights$h1) = "Heights in feet"
label(heights$h2) = "Heights in inches"
heights
table(heights[[`Heights in feet`]]) # Not correct
table(heights[`Heights in feet`]) # Not correct
table(heights$`Heights in feet`) # Not correct
非常感謝的想法。
不幸的是,基本索引操作不支持標簽。 與您所擁有的最相似的最接近的基本子集策略是
table(heights[, label(heights)=="Heights in feet"])
如果這是一個常見的操作,你可以重新定義一些操作符來為 data.frame 重載那種類型的東西。 例如
`%%.data.frame` <- function(x, lbl) {
x[,label(x)==lbl]
}
table(heights%%"Heights in feet")
你甚至可以制作一個作業版本
`%%<-` <- function(x, ...) UseMethod("%%<-")
`%%<-.data.frame` <- function(x, lbl, value) {
x[,label(x)==lbl] <- value
x
}
heights%%"Heights in feet" <- heights%%"Heights in feet"+1
當然這是非常不標准的,所以我可能不會推薦,但只是指出了這種可能性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.