Compute row amount and product in data.frame

I would like to add columns to my data.frame in R containing sums of rows and products. Consider the following data frame

xyz 1 2 3 2 3 4 5 1 2 

I want to get the following

 xyz sum prod 1 2 3 6 6 2 3 4 9 24 5 1 2 8 10 

I tried

  sum = apply(ages,1,add) 

but he gives me a row vector. Can someone please show me an effective command to summarize and product and add them to the original data frame as shown above?

+6
source share
3 answers

Try

  transform(df, sum=rowSums(df), prod=x*y*z) # xyz sum prod #1 1 2 3 6 6 #2 2 3 4 9 24 #3 5 1 2 8 10 

or

  transform(df, sum=rowSums(df), prod=Reduce(`*`, df)) # xyz sum prod #1 1 2 3 6 6 #2 2 3 4 9 24 #3 5 1 2 8 10 

Another option is to use rowProds from matrixStats

  library(matrixStats) transform(df, sum=rowSums(df), prod=rowProds(as.matrix(df))) 

If you use apply

  df[,c('sum', 'prod')] <- t(apply(df, 1, FUN=function(x) c(sum(x), prod(x)))) df # xyz sum prod #1 1 2 3 6 6 #2 2 3 4 9 24 #3 5 1 2 8 10 
+13
source

Another approach.

 require(data.table) # Create data dt <- data.table(x = c(1,2,5), y = c(2,3,1), z = c(3,4,2)) # Create index dt[, i := .I] # Compute sum and prod dt[, sum := sum(x, y, z), by = i] dt[, prod := prod(x, y, z), by = i] dt # Compute sum and prod using .SD dt[, c("sum", "prod") := NULL] dt dt[, sum := sum(.SD), by = i, .SDcols = c("x", "y", "z")] dt[, prod := prod(.SD), by = i, .SDcols = c("x", "y", "z")] dt # Compute sum and prod using .SD and list dt[, c("sum", "prod") := NULL] dt dt[, c("sum", "prod") := list(sum(.SD), prod(.SD)), by = i, .SDcols = c("x", "y", "z")] dt # Compute sum and prod using .SD and lapply dt[, c("sum", "prod") := NULL] dt dt[, c("sum", "prod") := lapply(list(sum, prod), do.call, .SD), by = i, .SDcols = c("x", "y", "z")] dt 
+3
source

The following can also be done, but you need to enter the column names:

 ddf$sum = with(ddf, x+y+z) ddf$prod = with(ddf, x*y*z) ddf xyz sum prod 1 1 2 3 6 6 2 2 3 4 9 24 3 5 1 2 8 10 

With data.table, another form could be:

 library(data.table) cbind(dt, dt[,list(sum=x+y+z, product=x*y*z),]) xyz sum product 1: 1 2 3 6 6 2: 2 3 4 9 24 3: 5 1 2 8 10 

A simpler version is suggested by @David Arenberg in the comments:

 dt[, ":="(sum = x+y+z, product = x*y*z)] 
+1
source

Source: https://habr.com/ru/post/978616/


All Articles