Reputation: 306
My task is to write a Stata-readable dataframe with variable labels and value labels. It appears that the package haven
is the most suitable one to do such an operation (better than readstata13
and foreign
).
I begin with creating the tibble:
library(haven)
x1 <- labelled(
sample(1:5),
c(Good = 1, Bad = 5)
)
x1
x2 <- labelled(
c("M", "F", "F", "F", "M"),
c(Male = "M", Female = "F")
)
x2
df <- tibble::data_frame(x1, x2, z = 1:5)
df
Then, I export the tibble
write_dta(df)
When I read it in Stata, the labels replace the real values (in x1
, 1 becomes equal to "Good" and 5 becomes equal to "Bad"). How can I read the tibble in Stata, in way such that the values remain from 1 to 5 and "Good" and "Bad" are stored as value labels?
Upvotes: 3
Views: 476
Reputation: 18585
It's possible but rather fiddly, you will have to attach labels manually using attr
1 function as in the example below.
# Attach variable and value labels to a new R data.frame
attr(df, "var.labels") <- c("my var label 1", "my var label 2")
# To create and attach value labels
val1 <- c(apple=10, beans=20)
val2 <- c(kg=1, bag=2)
attr(df, "label.table") <- list(val1, val2)
attr(df, "val.labels") <- c("val1", "val2")
# And finally describe the dataset
attr(df, "datalabel") <- "Collected from MWI 2013"
1The original solution was provided by Melanie Bacou and is available in this gist.
Upvotes: 2