Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate row sum and product in data.frame

Tags:

dataframe

r

apply

I would like to append a columns to my data.frame in R that contain row sums and products Consider following data frame

x    y     z
1    2     3
2    3     4
5    1     2

I want to get the following

x    y     z    sum    prod
1    2     3    6       6  
2    3     4    9       24 
5    1     2    8       10

I have tried

 sum = apply(ages,1,add)

but it gives me a row vector. Can some one please show me an efficient command to sum and product and append them to original data frame as shown above?

like image 280
Khurram Majeed Avatar asked Nov 24 '14 10:11

Khurram Majeed


1 Answers

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
like image 57
djhurio Avatar answered Nov 15 '22 15:11

djhurio