0

I have a data frame with 10 columns, of each the last five are five factors, each with 8 levels.

Isim_n20  Isim_n30  Isim_n50 Isim_n100 Isim_n1000  Intv_n20  Intv_n30
## 1 0.5514606 0.7765026 0.7680323 1.1443493  0.9927080   (0:0.6] (0.7:0.8]
## 2 3.5442714 0.0000000 1.5389077 2.6215133  0.9536723      >1.4   (0:0.6]
## 3 0.0000000 0.9690854 0.8298029 1.3201809  1.0433200   (0:0.6]   (0.9:1]
## 4 1.4641189 0.5637669 0.6108682 0.7588209  1.0154314      >1.4   (0:0.6]
## 5 0.7423402 1.0112330 0.8059606 0.8318506  1.0095619 (0.7:0.8]   (1:1.2]
## 6 0.9172783 1.0681631 0.8066872 0.8365090  1.0239348   (0.9:1]   (1:1.2]
##    Intv_n50 Intv_n100 Intv_n1000
## 1 (0.7:0.8]   (1:1.2]    (0.9:1]
## 2      >1.4      >1.4    (0.9:1]
## 3 (0.8:0.9] (1.2:1.4]    (1:1.2]
## 4 (0.6:0.7] (0.7:0.8]    (1:1.2]
## 5 (0.8:0.9] (0.8:0.9]    (1:1.2]
## 6 (0.8:0.9] (0.8:0.9]    (1:1.2]

I want to calculate percentage of levels for each factor separately (for the starts_with("Intv")columns and then create a data frame (table) to report the results. The multiple lines of function below work just fine but I am looking for a more elegant solution because I have to do this several times for several data sets.

prop1 <- prop.table(table(ism.50[6]))
prop2 <- prop.table(table(ism.50[7]))
prop3 <- prop.table(table(ism.50[8]))
prop4 <- prop.table(table(ism.50[9]))
prop5 <- prop.table(table(ism.50[10]))
prop <- cbind(prop1:prop5)

I am looking to get a table like this:

       (0:0.6] (0.6:0.7] (0.7:0.8] (0.8:0.9] (0.9:1] (1:1.2] (1.2:1.4]
prop1  0.1802    0.0812    0.0956    0.1064  0.0968  0.1364    0.0894
prop2  0.0990    0.0795    0.1113    0.1270  0.1127  0.1648    0.1021
prop3  0.0339    0.0597    0.1131    0.1492  0.1538  0.2130    0.1103
prop4  0.0042    0.0209    0.0921    0.1828  0.2032  0.2825    0.1303
prop5  0.0000    0.0000    0.0002    0.0422  0.4460  0.5075    0.0041
        >1.4
prop1 0.2140
prop2 0.2036
prop3 0.1670
prop4 0.0840
prop5 0.0000
  • 1
    Are you looking for something like this: `t(sapply(ism.50[6:10], function(x) prop.table(table(x))))`? – Ben Jul 29 '20 at 18:04
  • Perfect! Thank you @Ben. I was close to doing as you suggested but obviously I did not manage. May I ask, why ```sapply``` instead of ```apply```? – Stanciu Adrian Jul 29 '20 at 18:54
  • 1
    `lapply` works just fine, if you want a list returned to you. `sapply` is a "user-friendly" version and wrapper of `lapply` that in this case returns a simplified matrix (instead of a list), which I thought was closer to your desired output – Ben Jul 29 '20 at 19:35
  • I understand now, thank you. Indeed I wanted a matrix and not a list, as you noticed. – Stanciu Adrian Jul 30 '20 at 09:38

0 Answers0