Adding variable labels by attributes() function in R

Hi,
I would like to ask how to add variable labels so they are visible in attributes(data) ?
I know that there are some packages like "labelled" in R, but when I set variable labels by using it, it is not visible in attributes().
Another thing is that when I have got a dataframe and I have changed variable labels somehow it still keeps old labels instead of new ones. How to rectify this ?

attributes(mtcars)$names
# [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"  
 #[7] "qsec" "vs"   "am"   "gear" "carb"
datas <- structure(list(p1 = structure(c(3, 2, 2, 1, 2), label = "p1-I am most afraid of coronavirus-19", class = c(
  "labelled",
  "numeric"
)), p2 = structure(c(4, 2, 4, 4, 3), label = "p2-It makes me uncomfortable to think about coronavirus-19", class = c(
  "labelled",
  "numeric"
)), p3 = structure(c(2, 2, 4, 1, 2), label = "p3-My hands become clammy when I think about coronavirus-19", class = c(
  "labelled",
  "numeric"
))), row.names = c(NA, 5L), class = "data.frame")

v <- grep(pattern="p\\d", x=names(datas), value = FALSE)

items <- attributes(datas)$variable.labels[v]

and yet still items is NULL in spite of the fact that it is not, because variables' labels are present in a dataframe:

I would like to collect all variables' labels in one character vector named "items".

attributes(datas)[1]
$names
[1] "p1" "p2" "p3"

There is no separate variables component of attributes.

This is more/less what I want:

https://stackoverflow.com/questions/10181730/information-from-label-attribute-in-r-to-variable-labels-in-spss

I should have thought of Dr. Harrell's function. Try Hmisc::label and come back with questions?

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.