Labelled R-Dataset and Import to SPSS

79 Views Asked by At

I would like to change a dataset I landed in RStudio (R-4.1.1) to a sav-file. For this I want to label the variables with the function labelled from the package 'labelled' accordingly, i.e. with variables label and variables description. The problem I have is that I don't have just one dataset but several. I now wanted to write a loop in which the corresponding arguments for the 'labelled' function change. Example:

df #some data frame 
v_string1 <- c("easy", "hard", "very hard") #label for the first variable in df
v_string2 <- c("yes", "no") #labels for the second variable in df
v_num1 <- c(1,2,3) # possible values for the first variable in the data set.
v_num2 <- c(0,1) # possible values for the second variable in the data set

The variables v_string1-v_num2 are stored in another dataframe that I access, but for a quick example, let's assume for now that I only have two variables. My loop now looks like this:

df_new <- df

for (k in 1:dim(df)[2]){

m <- unique(v_num)

# List for the do.call-function
L_list <- list()

for (l in 1:m){
                 L_list[[v_string[l]]] = v_num[l]

                 }
df_new[,k] <- labelled(df[,k],
                        #the value labels
                        labels = do.call(c, L_list))
  
}

The code runs through and there is no error or warning message. But if I want to make an ordinal variable out of the variable that belongs to v_string1, for example, the labels are all deleted. I have also tried the to_factor-function, but for some reason the variable has no order, even though I set the argument to_factor(...,ordered = T). Does anyone have an idea what I could do?

0

There are 0 best solutions below