Yes, you can use DuckDB's random() function within a mutate in dplyr, but you need to ensure that the syntax is compatible with how dplyr translates operations to SQL for DuckDB. The issue might be related to how the random() function is being interpreted or how DuckDB handles random number generation in grouped operations.
To address this, you can use dbplyr::sql() to explicitly write SQL code within your dplyr pipeline, ensuring that DuckDB's random() function is called correctly. Here's how you can modify your code:
library(dplyr)
library(duckdb)
library(dbplyr)
duckdb_table |>
group_by(hcontract, measure_code) |>
mutate(random_val = dbplyr::sql("random()")) |>
arrange(random_val) |>
ungroup() |>
...
Explanation:
-
dbplyr::sql("random()"):
- The
dbplyr::sql() function allows you to embed raw SQL expressions within a dplyr pipeline. This ensures that DuckDB's random() function is directly passed to the SQL query without any translation issues.
-
Grouped Operations:
- When using
group_by, DuckDB will still respect the grouping in the SQL query, so the random() function will generate a random value for each row within the groups.
-
arrange(random_val):
- This will sort the rows within each group based on the random values, effectively shuffling the rows within each group.
Notes:
-
Reproducibility: If you need reproducible random numbers, DuckDB's random() function does not take a seed directly. To achieve reproducibility, you can set a seed at the DuckDB connection level using a SQL command like SET seed = 42; before running your query. For example:
con <- dbConnect(duckdb::duckdb())
dbExecute(con, "SET seed = 42;")
duckdb_table <- tbl(con, "your_table_name")
Then run your pipeline as above.
-
Performance: If you're working with a very large dataset, generating random numbers and sorting can be computationally expensive. Consider whether you need to shuffle the entire dataset or if a sample would suffice.
-
Debugging: If you still encounter issues, you can inspect the generated SQL query using show_query() to see how dplyr is translating your pipeline to SQL:
duckdb_table |>
group_by(hcontract, measure_code) |>
mutate(random_val = dbplyr::sql("random()")) |>
arrange(random_val) |>
ungroup() |>
show_query()
Alternative Approach (Pure SQL):
If you prefer to write the entire operation in SQL (especially for complex cases), you can use dbplyr::sql_query() or execute a raw SQL query directly on the DuckDB connection. For example:
result <- dbGetQuery(con, "
SELECT *,
random() AS random_val
FROM your_table_name
GROUP BY hcontract, measure_code
ORDER BY random_val
")
This approach bypasses dplyr entirely but might be useful if you need more control over the SQL query.
Let me know if you need further clarification or help!