w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to rearrange dataframe with likert variables into frequencies/percentages table in r?

To solve this problem, you need to:

  • First reshape the data to tall format (as opposed to wide). Use melt() from package reshape2 to do this.
  • Then recast your data in the desired shape, using cast(). This will give you a data frame with counts.
  • Finally, calculate the row-wise percentages. You can use apply().

Try this:

library(reshape2)

mdat <- melt(dat, id.vars=c("group"), variable.name="vars")
cdat <- dcast(mdat, group + vars ~ value, length)
cdat[, 3:6] <- t(apply(cdat[, 3:6], 1, function(x)x/sum(x)))
cdat

The result:

  group vars         1          2          3          4
1     1 var1 0.4615385 0.15384615 0.07692308 0.30769231
2     1 var2 0.3846154 0.23076923 0.38461538 0.00000000
3     1 var3 0.4615385 0.07692308 0.30769231 0.15384615
4     1 var4 0.5384615 0.23076923 0.15384615 0.07692308
5     2 var1 0.2941176 0.23529412 0.17647059 0.29411765
6     2 var2 0.2352941 0.00000000 0.52941176 0.23529412
7     2 var3 0.2352941 0.23529412 0.29411765 0.23529412
8     2 var4 0.4117647 0.05882353 0.17647059 0.35294118




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.