Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhilfi/b72bc29f88c0838e516c8f1e4bcba758 to your computer and use it in GitHub Desktop.
Save rhilfi/b72bc29f88c0838e516c8f1e4bcba758 to your computer and use it in GitHub Desktop.
label_variables_with_data_in_second_row #R
#########################################
### Example comments and labels ###
#########################################
## Hier lassen wir R nachschauen, ob die benötigten Packages installiert sind, falls nein: installieren wir sie.
list.of.packages <- c("Hmisc","janitor", "tidyverse", "rio")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
# update.packages(ask=TRUE)
## If you have a csv with variable labels on the second row and you want label the variables
data<-rio::import("http://www.pt-wissen.ch/stats/kleines_Beispiel_comments_labels.csv",skip=0, header=TRUE, encoding="UTF-8")
head(data)
to_retreive_labels<-rio::import("http://www.pt-wissen.ch/stats/kleines_Beispiel_comments_labels.csv", header=TRUE, nrow=1, encoding="UTF-8" )
Hmisc::label(data)=as.list(to_retreive_labels)
str(data)
## the problem is, now we need to convert all numeric variables to numeric, we could do this with mutate_at, but i think it is faster with import export;)
library(tidyverse)
data<-data %>%
dplyr::filter(id!="Personencode")
rio::export(data,"just_to_convert.csv")
data_2<-rio::import("just_to_convert.csv")
Hmisc::label(data_2)=as.list(to_retreive_labels)
## Example with Excel instead of csv
to_retreive_labels<-rio::import("http://www.pt-wissen.ch/stats/kleines_Beispiel_comments_labels.xlsx", sheet =1, col_names=TRUE,n_max=1 )
data<-janitor::clean_names(rio::import("http://www.pt-wissen.ch/stats/kleines_Beispiel_comments_labels.xlsx", sheet =1))
Hmisc::label(data)=as.list(to_retreive_labels)
library(tidyverse)
data<-data %>%
dplyr::filter(id!="Personencode")
rio::export(data,"just_to_convert.csv")
data_2<-rio::import("just_to_convert.csv")
Hmisc::label(data_2)=as.list(to_retreive_labels)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment