'R - changing values to labels permanently in labelled data
I have worked with haven and sjlabelled to try and work with data labels included on sav files.
Here is some example data (the real data is much larger with many more variables, values, labels, etc., and all values occur numerous times):
library(sjlabelled)
col1 <- c("a", "b", "c")
col2 <- c(1, 2, 3)
df <- data.frame(col1, col2)
labels <- c("x", "y", "z")
df <- set_labels(df, col2, labels = labels)
I know I can use as_label to manipulate the data frame using labels, subsetting using these labels, etc. However, I want to replace the values with the labels because some functions/processes revert the data to values and drop the labels entirely. I haven't been able to pin down when this will occur.
Using the example data, I want the original data frame to end up as the following, but instead of defining a new data frame, to just overwrite the values with the labels:
col1 <- c("a", "b", "c")
col2 <- c("x", "y", "z") # these were the labels but are now the values
df <- data.frame(col1, col2)
Solution 1:[1]
We can use get_labels
df$col2 <- get_labels(df$col2)[df$col2]
-output
> df
col1 col2
1 a x
2 b y
3 c z
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | akrun |
