Proper iteration, for example, applies with purrr

How can I achieve a consistent iteration using purrr :: map?

Here, how would I do it with a standard set of strings.

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, it is not too elegant, and I would prefer to do it with purrr. May (or may not) be faster.

+4
source share
2 answers

You can use pmapfor sequential iteration. Columns are used as arguments to any function that you use. In your example, you will have a function with three arguments.

For example, it pmapuses an anonymous function to do the work you do. Columns are passed to the function in the order in which they are in the data set.

pmap(df, function(a, b, c) {
     data.frame(var1 = a + b,
                var2 = c/2) 
     }  ) 

" " purrr tilde , .

pmap(df, ~data.frame(var1 = ..1 + ..2,
                var2 = ..3/2)  ) 

data.frame , pmap_dfr.

+5

, , :

df %>% dplyr::transmute(var1 = a+b,var2 = c/2)

( R: transform(df,var1 = a+b,var2 = c/2)[4:5])

, , pmap, @aosmith, dplyr::rowwise.

rowwise , , , , map, , pmap, , :

library(dplyr)
df %>% transmute(var3 = pmap(.,~median(c(..1,..2,..3))))
df %>% rowwise %>% transmute(var3 = median(c(a,b,c)))

( : res %>% split(seq(nrow(.))) %>% unname)

0

Source: https://habr.com/ru/post/1688042/


All Articles