简体   繁体   中英

apply function that takes row as an argument to each row in data.table

I have a data.table dt = structure(list(x = 1:3, y = 3:5), .Names = c("x", "y"), row.names = c(NA, -3L), class = c("data.table", "data.frame"))

Also, I have a given function that takes a row and dataset as an argument. For example, lets

function_sum <- function(i, dataset){
  x <- as.numeric(dataset[i,1])
  y <- as.numeric(dataset[i,2])
  x+y
}

I need to apply this function to each row in my dataset and have no idea how to do it.

It doesn't work dt[, function_sum(i=.SDrow, dataset=dt), by = seq_len(nrow(dt))]

Using your function_sum() function:

sapply(1:nrow(dt), function(i) function_sum(i,dt))
#[1] 4 6 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM