I would like to generate all possible populations in a 5-likert scale which values are the cumulative frequency by 0.1 in each level), e.g.:
[1] [2] [3] [4] [5]
1 0 0 0 0
0 1 0 0 0
...
0 0 0 0 1
0.9 0.1 0 0 0
0.9 0 0.1 0 0
...
0.8 0.2 0 0 0
0.8 0 0.2 0 0
...
0.8 0.1 0.1 0 0
and so on...
I have tried with some rudimentary loops like:
fin <- NULL
for (i in 1:10) {
a <- c(1-(i/10),0,0,0,0)
fin <- c(fin,a)
for (j in 1:10) {
b <- c(a[1],(j/10),0,0,0)
fin <- c(fin,b)
for (k in 1:10) {
c <- c(a[1],b[2],k/10,0,0)
fin <- c(fin,c)
for (l in 1:10) {
d <- c(a[1],b[2],c[3],l/10,0)
fin <- c(fin,d)
for (m in 1:10) {
e <- c(a[1],b[2],c[3],d[4],m/10)
fin <- c(fin,e)
}
}
}
}
}
dat <- as.data.frame(matrix(fin, ncol = 5, byrow = T))
head(dat)
a <- NULL
for (i in 1:111110) {
if(rowSums(dat[i,])==1)
{b <- dat[i,]
a <- c(a,b)}
else{
next
}
}
dat <- as.data.frame(matrix(fin, ncol = 5, byrow = T))
I know it is not smart neither efficient but rows where sum = 1 are some of the cases I want to have, but it is insufficient.
I really appreciate any help. Thanks in advance.
Create vector containing all allowed values
values <- seq(0, 1, by=0.1)
values
Returns:
[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
Using base R expand.grid
to get all possible combinations of these values for five variables:
df <- expand.grid(A1 = values, A2 = values, A3 = values, A4 = values, A5 = values)
Calculate row wise sum using rowSums
:
df$TestSum <- rowSums(df)
Keep only rows where the TestSum is 1 (and also only keep the first 5 columns, we don't need the TestSum column anymore):
result <- df[df$TestSum == 1, 1:5]
head(result)
Returns:
A1 A2 A3 A4 A5
11 1.0 0.0 0 0 0
21 0.9 0.1 0 0 0
31 0.8 0.2 0 0 0
41 0.7 0.3 0 0 0
51 0.6 0.4 0 0 0
61 0.5 0.5 0 0 0