I'm trying to return a list using mutate and rowwise but get the error shown in the code. These questions Q1 Q2 helped, but I'd like to keep it simple by iterating over rows using rowwise()
, and the questions are 3yr 7mth old. Thanks.
library(tidyverse)
df <- data.frame(Name=c("a","a","b","b","c"),X=c(1,2,3,4,5), Y=c(2,3,4,2,2))
TestFn <- function(X,Y){
Z <- list(X*5,Y/2,X+Y,X*2+5*Y)
return (Z)
}
#this works
SingleResult <- TestFn(5,20)
#error - Error in mutate_impl(.data, dots) : incompatible size (4), expecting 1 (the group size) or 1
dfResult <- df %>%
rowwise() %>%
mutate(R=TestFn(X,Y))
Your
TestFn
returns a 4 elements list per row, which can't really be fit in a row; You can wrap the returned elements in a vector first so the returned list is a single element list:rowwise
is usually not as efficient, if you want to vectorize the solution, you can calculate the four expressions firstly and then transpose the result: