Search code examples
rdataframesum

R- How to group a series of values by the hundredth digit after the decimal separator


I have a data frame with two columns. First column is "Ratio", and the second column has numbers that represent the value measured at that ratio. For example:

   Ratio Intensity
1  0.000  1387.785
2  0.001  1325.254
3  0.003  1307.926
4  0.004  1286.817
5  0.006  1276.197
6  0.007  1251.381
7  0.008  1249.394
8  0.010  1251.923
9  0.011  1263.183
10 0.013  1265.272
11 0.014  1303.354
12 0.015  1336.920
13 0.017  1362.173
14 0.018  1395.946
...

I want to sort the data and sum the intensity:

   Ratio Intensity
1  0.00  1297.822
2  0.01  1311.253
3  0.02  1307.926
4  0.03  1286.817
5  0.04  1276.197
6  0.05  1251.381
7  0.06  1249.394
8  0.07  1251.923
9  0.08  1263.183
10 0.09  1265.272
11 0.10  1303.354
12 0.11  1336.920
13 0.12  1362.173
14 0.13  1395.946

How can I write a script in R to sum and export into a new csv file? Thank you!


Solution

  • floor and aggregate maybe

    > aggregate(Intensity ~ cbind(Ratio=I(floor(Ratio*100)/100)), d, mean)
      Ratio Intensity
    1  0.00  1297.822
    2  0.01  1311.253
    

    Data:

    > dput(d)
    structure(list(Ratio = c(0, 0.001, 0.003, 0.004, 0.006, 0.007, 
    0.008, 0.01, 0.011, 0.013, 0.014, 0.015, 0.017, 0.018), Intensity = c(1387.785, 
    1325.254, 1307.926, 1286.817, 1276.197, 1251.381, 1249.394, 1251.923, 
    1263.183, 1265.272, 1303.354, 1336.92, 1362.173, 1395.946)), class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
    "14"))