r - How to reflow long to wide only part and summarise the rest? -
i need arrange table performing formatting, table like
dt <- read.table(text = "year st_id n overall metric1 metric2 1999 205 386 96.3 0 0 1999 205 15 0 0 0 1999 205 0 0 0 0 1999 205 0 0 0 na 2000 205 440 100 0 0 2000 205 0 0 0 0 2000 205 0 0 na 0 2000 205 0 0 0 na", header = true)
i need obtain following "output" table.
year st_id 1 2 3 4 overall metric1 metric2 1999 205 386 15 0 0 96.3 0 na 2000 205 440 0 0 0 100 na na . .
in columns on right, want aggregate instances of na => na else sum(values)
how can achieve using r?
library(tidyr) a=aggregate(.~year,xy[-(2:3)],sum,na.action=function(x)x) xy[1:3]%>%group_by(year)%>%mutate(n_=1:4)%>%spread(n_,n,sep="")%>%merge(a,by="year") year st_id n_1 n_2 n_3 n_4 overall metric1 metric2 1 1999 205 386 15 0 0 96.3 0 na 2 2000 205 440 0 0 0 100.0 na na
hope helps.
i think there can better way aggregate. eg na.action
should take identity function(a function returns input) such i
function in base r. although i
function changes class of object asis
, challenge me within aggregate function
. class(i(xy))
.
Comments
Post a Comment