Row-wise iteration like apply with purrr

前端 未结 3 905
北荒
北荒 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:39

    You are free to always make a wrapper around a function you "like".

    rmap <- function (.x, .f, ...) {
        if(is.null(dim(.x))) stop("dim(X) must have a positive length")
        .x <- t(.x) %>% as.data.frame(.,stringsAsFactors=F)
        purrr::map(.x=.x,.f=.f,...)
    }
    

    apply the new function rmap (rowwisemap)

    rmap(df1,~{
        var1 <- (.x[[1]] + .x[[2]])
        var2 <- .x[[3]]/2
        return(data.frame(var1 = var1, var2 = var2))
        })
    

    Additional Info: (eval from top to bottom)

    df1 <- data.frame(a=1:3,b=1:3,c=1:3)
    m   <- matrix(1:9,ncol=3)
    
    apply(df1,1,sum)
    rmap(df1,sum)
    
    apply(m,1,sum)
    rmap(m,sum)
    
    apply(1:10,1,sum)  # intentionally throws an error
    rmap(1:10,sum)     # intentionally throws an error
    

提交回复
热议问题