Creating Lists from a Character String

Perhaps my brain does not work today, but I can’t figure out how to create a list of 2 character strings.

I have currently received

scale_lab
[1] "Very Poor"  "Poor"       "Average"    "Good"       "Very Good" 
[6] "Don't Know"

and

scale_rep
[1] "1" "2" "3" "4" "5" "9"

So what I want to do is combine them into a list so that 1 = very bad, 2 = poor, etc.

+3
source share
2 answers

Just use names()to assign it:

> scale_lab <- c("Very Poor", "Poor", "Average", "Good", 
+                "Very Good", "Don't Know")
> scale_rep <- c("1","2","3","4","5","9")
> names(scale_lab) <- scale_rep
> scale_lab
           1            2            3            4            5            9
 "Very Poor"       "Poor"    "Average"       "Good"  "Very Good" "Don't Know"
> scale_lab["9"]
           9
"Don't Know"
>
+3
source

Alternatively, you can save it as a factor (equivalent to the R categorical variable)

scale_rep <- factor(scale_rep, label=scale_lab)

If you need to use numbers for some ordinal data, you can always return to numbers:

as.numeric(scale_rep) 

Although, I would transcode DK as NA

scale_rep[scale_rep == 9] <- NA
+2
source

Source: https://habr.com/ru/post/1767812/


All Articles