jeudi 20 février 2020

How can I create a for loop with "if" condition that will extract label from a vector when the label is present?

I often work with datasets from spss which usually have variable labels embedded with.

What I would like to do is to have a neat option to extract labels of those variables, if they are present.

I think I found the proper code, but there is one error that I don't understand.

Here's the code.

First, I want to extract lables from a list of vectors:

lista2 <- sapply(list(variable1, variable2, variable3), function(x) {attr(x, which = "label")})

I end up with another list, for instance:

[[1]]
[1] "Q1. Wska? swoj? p?e?:"

[[2]]
[1] "Q3. Jaki masz kolor oczu?"

[[3]]
NULL

Then, I create an empty vector:

labels <- c()

And in the end, I want to create the loop:

for(i in length(lista2)) {if(is.null(lista2[[i]]) == F) {labels[[i]] <- lista2[[i]]}
else{labels[[i]] <- c("z")  }}

Unfortunately, the first part of if does not work.

[1] NA  NA  "z"

But when I do it manually, that is, I write for instance

labels[[1]] <- lista2[[1]]

Everything works.

I will be grateful for any help.

Aucun commentaire:

Enregistrer un commentaire