Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Row-wise iteration like apply with purrr

Tags:

r

apply

purrr

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.

like image 357
matsuo_basho Avatar asked Oct 23 '17 22:10

matsuo_basho


People also ask

Is purrr faster than for loops?

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.

What does rowwise () do in R?

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.

What does PMAP do in R?

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.

What does row wise mean?

rowwise (not comparable) By rows; one row at a time.


1 Answers

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.

like image 87
aosmith Avatar answered Sep 21 '22 13:09

aosmith