Question

I'm having trouble assigning value labels from lists to numeric variables. I've got a dataset (in form of a list()) containing eleven variables. The first five variables each have individual value levels, the last six each use the same 1-5 scale. I created lists with value labels for each of the first five variables and one for the scale. Now I would like to automatically assign the labels from those lists to my variables.

I've put my eleven variables in a list to be able to use mapply().

Here's an example of my current state:

# Example variables:
a <- c(1,2,3,4) # individual variable a
b <- c(1,2,2,1) # individual variable b
c <- c(1,2,3,4,5) # variable c using the scale
d <- c(1,2,3,4,5) # variable d also using the scale


mydata <- list(a,b,c,d)

# Example value labels:
lab.a <- c("These", "are", "value", "labels")
lab.b <- c("some", "more")
lab.c <- c("And", "those", "for", "the", "scale")

labels.abc <- list(lab.a, lab.b, lab.c)

# Assigning labels in two parts
part.a <- mapply(function(x,y) factor(as.numeric(x), labels = y, exclude = NA), mydata[1:2], labels.abc[1:2])
part.b <- mapply(function(x,y) factor(as.numeric(x), labels = y, exclude = NA), mydata[3:4], labels.abc[3])

Apart from not being able to combine the two parts, my major problem is the output format. mapply() gives the result in form of a matrix, where I need again a list containing the specific variables.

So, my question is: How can I assign the value labels in an automated procedure and as the result again get a list of variables, which now contain labeled information instead of numerics?

I'm quite lost here. Is my approach with mapply() generally doable, or am I completely on the wrong track?

Thanks in advance! Please comment if you need further information.

Was it helpful?

Solution

Problem solved!

Thanks @agstudy for pointing out the SIMPLIFY = FALSE argument, which prevents mapply() from reducing the result to a matrix.

The correct code is

part.a <- mapply(function(x,y) factor(as.numeric(x), labels = y, exclude = NA), mydata[1:2], labels.abc[1:2], SIMPLIFY = FALSE)

This provides exactly the same format of output as was put in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top