[英]Setting variable attributes via subsetting a dataframe
我想通過子集數據幀並遍歷字符向量來設置數據幀中某些變量的屬性(“ full.name”)。 我嘗試了兩種解決方案,但均無效(varsToPrint是包含變量的字符向量,questionLabels是包含問題標簽的字符向量):
樣本數據:
jtiPrint <- data.frame(question1 = seq(5), question2 = seq(5), question3=seq(5))
questionLabels <- c("question1Label", "question2Label")
varsToPrint <- c("question1", "question2")
解決方案1:
attrApply <- function(var, label) {
`<-`(attr(var, "full.name"), label)
}
mapply(attrApply, jtiPrint[varsToPrint], questionLabels)
解決方案2:
i <- 1
for (var in jtiPrint[varsToPrint]) {
attr(var, "full.name") <- questionLabels[i]
i <- i + 1
}
所需的輸出(例如變量1):
attr(jtiPrint$question1, "full.name")
[1] "question1Label"
問題似乎出在解決方案2中,R將屬性設置為僅包含一個變量(索引變量)的新數據幀。 但是,我不明白為什么解決方案1不起作用。 任何想法如何解決這兩種方式中的任何一種?
解決方案1 :
函數是'attr<-'
而不是'<-'(attr...)
,同樣需要設置SIMPLIFY=FALSE
(否則返回矩陣而不是列表),然后調用as.data.frame
:
attrApply <- function(var, label) {
`attr<-`(var, "full.name", label)
}
df <- as.data.frame(mapply(attrApply,jtiPrint[varsToPrint],questionLabels,SIMPLIFY = FALSE))
> str(df)
'data.frame': 5 obs. of 2 variables:
$ question1: atomic 1 2 3 4 5
..- attr(*, "full.name")= chr "question1Label"
$ question2: atomic 1 2 3 4 5
..- attr(*, "full.name")= chr "question2Label"
解決方案2 :
您需要在data.frame的列上設置屬性,在列的副本上設置屬性:
for(i in 1:length(varsToPrint)){
attr(jtiPrint[[i]],"full.name") <- questionLabels[i]
}
> str(jtiPrint)
'data.frame': 5 obs. of 3 variables:
$ question1: atomic 1 2 3 4 5
..- attr(*, "full.name")= chr "question1Label"
$ question2: atomic 1 2 3 4 5
..- attr(*, "full.name")= chr "question2Label"
$ question3: int 1 2 3 4 5
無論如何,請注意,這兩種方法會導致不同的結果。 實際上, mapply
解決方案返回先前data.frame
的子集(因此沒有列3),而第二種方法修改了現有的jtiPrint
data.frame
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.