How do I introduce row names to a function in R

Posted by Tahnoon Pasha on Stack Overflow See other posts from Stack Overflow or by Tahnoon Pasha
Published on 2012-10-31T08:54:36Z Indexed on 2012/10/31 17:00 UTC
Read the original article Hit count: 245

Filed under:
|

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)

© Stack Overflow or respective owner

Related posts about r

    Related posts about user-defined-functions