0
votes

I have a dataframe with several vectors of ordered factors that could take the values 1-4. v2 does not have any instances of value 3. Here's a basic example:

myData <- data.frame(v1=factor(c(1, 1, 2, 2, 3, 3, 4, 4),
                               levels=c(1, 2, 3, 4),
                               ordered=TRUE),
                     v2=factor(c(1, 1, 2, 2, 4, 4, 4, 4),
                               levels=c(1, 2, 3, 4),
                               ordered=TRUE))
myData
#   v1 v2
# 1  1  1
# 2  1  1
# 3  2  2
# 4  2  2
# 5  3  4
# 6  3  4
# 7  4  4
# 8  4  4

levels(myData$v2)
# [1] "1" "2" "3" "4"

I needed to impute missing data, so I dropped unused levels across all columns (e.g., level 3 in v2):

myData <- droplevels(myData)
levels(myData$v2)
# [1] "1" "2" "4"

Now I want to create some Likert plots, but all columns in the dataframe need to have the same number of response options (i.e., the same number of levels).

I've defined the max levels found in the dataframe programmatically in an object called L. So in this case, the result is an object L:

L <- c(1, 2, 3, 4)

I need to make sure that every column in the dataframe has levels L. For v2, this will mean that there are 0 observations with level 3. I have more than just two columns, so I need to run the solution across all columns.

The apply style approaches I've tried just resulted in NAs.

1
Seems like just myData[] <- lapply(myData, `levels<-`, L) ? - David Arenburg
Thanks, @DavidArenburg. I did not know about levels<-. That's helpful. However, while this does add the missing level, 4's in 1 1 2 2 4 4 4 4 become 3's 1 1 2 2 3 3 3 3. I need the values to remain the same 1 1 2 2 4 4 4 4 but have levels Levels: 1 < 2 < 3 < 4 (so adding back unused levels without changing values). - Eric Green
Hmmm... That's kind of odd. Never encountered this behavior before... This seem to work properly myData[] <- lapply(myData, factor, levels = L) though it beats me what happening with levels<-. - David Arenburg
Did that solve your problem or not? - David Arenburg
yes, that seems to work. thanks. missed your earlier message. for some reason i did not see the suggestion after the ... - Eric Green

1 Answers

0
votes

via @DavidArenburg:

myData[] <- lapply(myData, factor, levels = L)