TidierOrg / TidierData.jl

Tidier data transformations in Julia, modeled after the dplyr/tidyr R packages.
MIT License
86 stars 7 forks source link

Implement `dplyr::rowwise()` functionality using `DataFrames` and `ByRow()` #49

Open christophscheuch opened 1 year ago

christophscheuch commented 1 year ago

So in dplyr, I can group data into individual rows using rowwise() and functions will compute results for each row. Here is an example:

library(dplyr)
library(purrr)

generate_random_strings_vector <- function() {
  colors <- c("red", "blue", "green", "yellow", "orange")
  sample(colors, sample(1:5, 1), replace = TRUE)
}

df <- tibble(
  id = 1:500
) |> 
  mutate(colors = map(1:n(), ~generate_random_strings_vector()))

df |> 
  rowwise() |> 
  mutate(number_of_colors = length(colors))

If I want to do the same in Julia using DataFrames.jl, I'd do it like this:

using DataFrames, Random

function generate_random_strings_vector()
    colors = ["red", "blue", "green", "yellow", "orange"]
    return rand(colors, rand(1:5))
end

df = DataFrame(id = 1:500)
df[!, :colors] = [generate_random_strings_vector() for _ in 1:nrow(df)]

transform(df, :colors => ByRow(length) => :num_colors)

Does it make sense to have something like that in TidierData.jl?

@chain df @rowwise() @mutate(num_colors = length(colors))
kdpsingh commented 1 year ago

Thanks for bringing this up, @christophscheuch. This use case has definitely been on my mind.

There are a couple of things that make this tricky (but definitely not impossible) to implement.

One of them is that we need to use metadata fields within the data frame to keep track of whether a data frame is currently in rowwise mode. This is somewhat similar to @group_by except that grouping is already tracked within DataFrames.jl whereas rowwise is not. Once this ability is implemented, we need to make all other macros aware of it and make sure that it plays nicely with grouping and ungrouping.

I'm saving this for a later update but agree we should add it.