How do I achieve row-wise iteration using purrr::map?
Here's how I'd do it with a standard row-wise apply.
df <- data.frame(a = 1:10, b = 11:20, c = 21:30) lst_result <- apply(df, 1, function(x){ var1 <- (x[['a']] + x[['b']]) var2 <- x[['c']]/2 return(data.frame(var1 = var1, var2 = var2)) })
However, this is not too elegant, and I would rather do it with purrr. May (or may not) be faster, too.
The purrr library is an incredible tool to help make your code faster and more efficient by eliminating for loops and taking advantage of R's functional abilities.
rowwise() allows you to compute on a data frame a row-at-a-time. This is most useful when a vectorised function doesn't exist. Most dplyr verbs preserve row-wise grouping.
In pmap() , you have to store all your input vectors in a single list. This functionality allows pmap() to handle any number of input vectors.
rowwise (not comparable) By rows; one row at a time.
You can use pmap
for row-wise iteration. The columns are used as the arguments of whatever function you are using. In your example you would have a three-argument function.
For example, here is pmap
using an anonymous function for the work you are doing. The columns are passed to the function in the order they are in the dataset.
pmap(df, function(a, b, c) { data.frame(var1 = a + b, var2 = c/2) } )
You can use the purrr tilde "short-hand" for an anonymous function by referring to the columns in order with numbers preceded by two dots.
pmap(df, ~data.frame(var1 = ..1 + ..2, var2 = ..3/2) )
If you want to get these particular results as a data.frame instead of a list, you can use pmap_dfr
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With