r - How do I add a row to a data frame with totals? -


i have data frame add additional row totals values columns. example, let's have data:

x <- data.frame(language=c("c++", "java", "python"),                  files=c(4009, 210, 35),                  loc=c(15328,876, 200),                  stringsasfactors=false)     

data looks this:

  language files   loc 1      c++  4009 15328 2     java   210   876 3   python    35   200 

my instinct this:

y <- rbind(x, c("total", colsums(x[,2:3]))) 

and works, computes totals:

> y   language files   loc 1      c++  4009 15328 2     java   210   876 3   python    35   200 4    total  4254 16404 

the problem files , loc columns have been converted strings:

> y$loc [1] "15328" "876"   "200"   "16404" 

i understand happening because created vector c("total", colsums(x[,2:3]) inputs both numbers , strings, , it's converting elements common type of vector elements same. same thing happens files , loc columns.

what's better way this?

do need language column in data, or more appropriate think of column row.names? change data.frame 4 observations of 3 variables 4 observations of 2 variables (files & loc).

x <- data.frame(files=c(4009, 210, 35), loc=c(15328,876, 200), row.names=c("c++", "java", "python"), stringsasfactors=f)     x["total" ,] <- colsums(x)   > x        files   loc c++     4009 15328 java     210   876 python    35   200 total   4254 16404 

Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -