Row-wise iteration like apply with purrr

前端 未结 3 902
北荒
北荒 2021-01-30 13:18

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         


        
3条回答
  •  星月不相逢
    2021-01-30 13:49

    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.

提交回复
热议问题