Ordered Numeric Variable in R

Hi All,

Quite a strange request, but I wondered if it was possible in R to impose an order on a numeric variable?

So, for example, I have been previously working with my variable as an ordinal factor with three levels.

data$x1 <- factor(data$x1, ordered = TRUE, levels = c("3", "2", "1"))

As you can see, the ordinal factor variable is also a number on a Likert-like scale, where 3 is perceived as worse than 1.

Yet, one of the routines I've been working with recently only accepts numeric variables. Therefore, I wondered if it was possible to transform it into 'as.numeric', but command that 3<2<1?

Yes, that's what levels does. Post some sample data?

Hi @technocrat. I appreciate your feedback, but the problem is with my variable expressed as a levelled factored and the procedure I am using only considers numeric variables.

If your real life issue is exactly like your example, you would seem to get your requirement trivially. If your example does not represent your real life challenge, more finesse is likely required.

(x1 <- factor(c(3,2,1,2,3,1,2), ordered = TRUE, levels = c("3", "2", "1")))

(rev_num_x1 <- as.integer(x1))

In this example we have data 3,2,1,2,3,1,2 because you have set the factor as ordinal the integer representation of the factors is already numbers that map directly to the old 3/2/1 are themselves 1/2/3 so now as you go through the vector ; where you had a 3 before you have a 1 , where you had a 2 you keep 2's and where you had 1s you have 3.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.