(in R) Add metadata from a vector to a set of columns of a dataframe?

做~自己de王妃 提交于 2021-01-29 12:32:59

问题


I would like to use values from a character vector that I created as label attributes for a set of variables in a dataframe.

I thought this simple solution should work, yet it does not:

x <- rep("text", time=19) %>% 
  paste(1:19, sep = " ")  #character vector with names of label attributes I want

attr(mydataframe[var_names], "label") <- x #var_names and x have the same length

Thanks for your help!


回答1:


Hmisc supports column labels. Using the built in data frame anscombe having 8 columns:

library(Hmisc)

x <- paste("label", i)

for(i in seq_along(anscombe)) label(anscombe[[i]]) <- x[i]
Label(anscombe)

giving:

label(x1)       <- 'label 1'
label(x2)       <- 'label 2'
label(x3)       <- 'label 3'
label(x4)       <- 'label 4'
label(y1)       <- 'label 5'
label(y2)       <- 'label 6'
label(y3)       <- 'label 7'
label(y4)       <- 'label 8'


来源:https://stackoverflow.com/questions/52116172/in-r-add-metadata-from-a-vector-to-a-set-of-columns-of-a-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!