How do I introduce row names to a function in R
- by Tahnoon Pasha
Hi I have a utility function I've put together to insert rows into a dataframe below. If I was writing out the formula by hand I would put something like
newframe=rbind(oldframe[1:rownum,],row_to_insert=row_to_insert,oldframe[(rownum+1:nrow(oldframe),] to name row_to_insert. Could someone tell me how to do this in a function?
Thanks
insertrows=function (x, y, rownum)
{
newframe = rbind(y[1:rownum, ], x, y[(rownum + 1):nrow(y),
])
return(data.frame(newframe))
}
MWE of some underlying data added below
financials=data.frame(sales=c(100,150,200,250),some.direct.costs=c(25,30,35,40),other.direct.costs=c(15,25,25,35),indirect.costs=c(40,45,45,50))
oldframe=t(financials)
colnames(oldframe)=make.names(seq(2000,2003,1))
total.direct.costs=oldframe['some.direct.costs',]+oldframe['other.direct.costs',]
newframe=total.direct.costs
n=rownum=3
oldframe=insertrows(total.direct.costs=newframe,oldframe,n)