I have a vector like the following
label_names<-c("A","B","C")
I also have the following data.frame
df<- data.frame(var1=1:5,var2=1:5, var3=1:5)
What I want to do is to assign label_names to my df. Then I want to write the data.frame as .dta file to read the labelled data in Stata. Please notice that the original vector I have is larger than this, so I need a general solution.
In my limited experience, R does not use labels as often as Stata. Still you can do it. You need two packages: expss and haven:
In r, use expss::apply_labels to assign variable labels and value labels. I only use variable labels for the purpose of demonstration:
df <- data.frame(year = c(2017, 2018, 2019),
age = c(25, 30, 40),
bmi = c(23.2, 28.3, 32))
# assign labels in r
df = expss::apply_labels(df,
year = "Survey year",
age = "Age, years",
bmi = "BMI, kg/m2"
)
# export to Stata
haven::write_dta(df, "havenstata.dta")
In Stata, you can check:
. des
Contains data from C:\...\havenstata.dta
obs: 3
vars: 3 24 Dec 2019 22:17
size: 72
------------------------------------------------------------------------------------------------------
storage display value
variable name type format label variable label
------------------------------------------------------------------------------------------------------
year double %10.0g Survey year
age double %10.0g Age, years
bmi double %10.0g BMI, kg/m2
------------------------------------------------------------------------------------------------------
Sorted by:
Although there are some solutions, I think it might be easier to label data in Stata after exported to Stata.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With