简体   繁体   中英

Assign results of apply to multiple columns of data frame

I would like to process all rows in data frame df by applying function f to every row. As function f returns numeric vector with two elements I would like to assign individual elements to new columns in df .

Sample df , trivial function f returning two elements and my trial with using apply

df <- data.frame(a = 1:3, b = 3:5)

f <- function (a, b) {
  c(a + b, a * b)
}

df[, c('apb', 'amb')] <- apply(df, 1, function(x) f(a = x[1], b = x[2]))

This does not work results are assigned by columns:

> df
  a b apb amb
1 1 3   4   8
2 2 4   3   8
3 3 5   6  15

You could also use Reduce instead of apply as it is generally more efficient. You just need to slightly modify your function to use cbind instead of c

f <- function (a, b) {
  cbind(a + b, a * b) # midified to use `cbind` instead of `c`
}

df[c('apb', 'amb')] <- Reduce(f, df)
df
#   a b apb amb
# 1 1 3   4   3
# 2 2 4   6   8
# 3 3 5   8  15

Note : This will only work nicely if you have only two columns (as in your example), thus if you have more columns in you data set, run this only on a subset

You need to transpose apply results to get what you want :

df[, c('apb', 'amb')] <- t(apply(df, 1, function(x) f(a = x[1], b = x[2])))

> df
  a b apb amb
1 1 3   4   3
2 2 4   6   8
3 3 5   8  15

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