Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
christophscheuch opened this issue Sep 27, 2023 · 1 comment

Comments

@christophscheuch
Copy link

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
Copy link
Member

kdpsingh commented Sep 27, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants