How can I do a pivot table in R with a calculated field? -


i'm trying construct pivot table calculated field in r. data frame similar this:

   number   hour    tot      cefe  sell         1  09:00    50         2     1         1  10:00    52        na    na         1  11:00    72         4     1         1  12:00    96         3    na         1  13:00    90         4     1         1  14:00    98         2     1         2  08:00    38         4     1         2  09:00   427        16     2         2  10:00   493        16     1         2  11:00   340        16    na         2  12:00   571        20     2         2  13:00   547        23     2         2  14:00   578        25     4 

i need construct pivot table using "number" variable rows, "hour" columns , result of "cefe/tot" value. don´t want add column or generate data frame don't know how it. tried cast function considers "sell" variable value. idea?

you can dplyr , tidyr, although script technically create new column part of transformation.

library(dplyr) library(tidyr)  x %>%   mutate(cefetot = cefe/tot) %>%   select(number, hour, cefetot) %>%   spread(key = hour, value = cefetot) 

Comments