[R] generate ordered categorical variable in R
Marc Schwartz
marc_schwartz at me.com
Wed Sep 16 19:33:31 CEST 2015
> On Sep 16, 2015, at 12:11 PM, thanoon younis <thanoon.younis80 at gmail.com> wrote:
>
> Dear R- users
>
> I want to generate ordered categorical variable vector with 200x1 dimension
> and from 1 to 4 categories and i tried with this code
>
> Q1=runif(200,1,4) the results are not just 1 ,2 3,4, but the results with
> decimals like 1.244, 2.342,4,321 and so on ... My question how can i
> generate a vector and also a matrix with orered categorical variables and
> without decimals just 1,2,3 ,4 ,1,2,3,4, ....
>
> Many thanks in advance
You are sampling from a uniform distribution on the continuous interval from 1 to 4.
See ?sample
set.seed(1)
> sample(4, 200, replace = TRUE)
[1] 2 2 3 4 1 4 4 3 3 1 1 1 3 2 4 2 3 4 2 4 4 1 3 1 2 2 1 2 4 2 2 3 2
[34] 1 4 3 4 1 3 2 4 3 4 3 3 4 1 2 3 3 2 4 2 1 1 1 2 3 3 2 4 2 2 2 3 2
[67] 2 4 1 4 2 4 2 2 2 4 4 2 4 4 2 3 2 2 4 1 3 1 1 1 1 1 3 4 4 4 2 2 4
[100] 3 3 2 2 4 3 1 1 2 4 3 4 3 2 2 1 1 3 1 2 3 4 2 2 1 4 2 3 1 1 3 3 1
[133] 1 3 4 3 3 3 4 3 3 3 1 2 3 2 1 3 1 4 3 3 2 2 3 1 3 1 2 1 2 4 2 4 4
[166] 2 1 2 3 2 3 4 4 2 2 4 3 3 3 4 2 1 4 3 4 1 4 3 4 3 3 2 1 4 2 3 1 4
[199] 2 4
Here, the result is a vector of integers.
set.seed(1)
> sample(factor(1:4), 200, replace = TRUE)
[1] 2 2 3 4 1 4 4 3 3 1 1 1 3 2 4 2 3 4 2 4 4 1 3 1 2 2 1 2 4 2 2 3 2
[34] 1 4 3 4 1 3 2 4 3 4 3 3 4 1 2 3 3 2 4 2 1 1 1 2 3 3 2 4 2 2 2 3 2
[67] 2 4 1 4 2 4 2 2 2 4 4 2 4 4 2 3 2 2 4 1 3 1 1 1 1 1 3 4 4 4 2 2 4
[100] 3 3 2 2 4 3 1 1 2 4 3 4 3 2 2 1 1 3 1 2 3 4 2 2 1 4 2 3 1 1 3 3 1
[133] 1 3 4 3 3 3 4 3 3 3 1 2 3 2 1 3 1 4 3 3 2 2 3 1 3 1 2 1 2 4 2 4 4
[166] 2 1 2 3 2 3 4 4 2 2 4 3 3 3 4 2 1 4 3 4 1 4 3 4 3 3 2 1 4 2 3 1 4
[199] 2 4
Levels: 1 2 3 4
Here, the result is a factor.
set.seed(1)
> sample(factor(c("A", "B", "C", "D")), 200, replace = TRUE)
[1] B B C D A D D C C A A A C B D B C D B D D A C A B B A B D B B C B
[34] A D C D A C B D C D C C D A B C C B D B A A A B C C B D B B B C B
[67] B D A D B D B B B D D B D D B C B B D A C A A A A A C D D D B B D
[100] C C B B D C A A B D C D C B B A A C A B C D B B A D B C A A C C A
[133] A C D C C C D C C C A B C B A C A D C C B B C A C A B A B D B D D
[166] B A B C B C D D B B D C C C D B A D C D A D C D C C B A D B C A D
[199] B D
Levels: A B C D
Here, the result is a factor.
Just depends upon what you want for the categorial variable.
Regards,
Marc Schwartz
More information about the R-help
mailing list