如何利用tidyverse规整地追加多列?以生成Gamma分布列为例
Got it, let's work through this step by step! You want to append 30 columns of Gamma distribution values to your existing data frame using tidyverse tools, and you've specified using dgamma(1:30, shape, rate) for each row. Here's a clean, efficient way to do this:
First, let's start with your sample data and load the tidyverse package:
library(tidyverse) # Your sample data frame df <- data.frame( rank = 1:3, shape = c(16, 0.2, 4), rate = c(13, 0.4, 0.2) )
The key idea here is to generate a list column where each entry contains the 30 Gamma values for that row, then expand that list column into individual columns. This avoids writing 30 separate mutate calls, which would be tedious.
Here's the code to do that:
df_with_gamma <- df %>% # Process each row individually rowwise() %>% # Create a list column with 30 Gamma values per row mutate(gamma_values = list(dgamma(1:30, shape = shape, rate = rate))) %>% # Expand the list column into 30 separate columns, named gamma_1 to gamma_30 unnest_wider(gamma_values, names_repair = ~str_c("gamma_", 1:30)) %>% # Turn off rowwise processing (good practice after using rowwise()) ungroup()
Let's break this down:
rowwise()tells dplyr to operate on each row independently, so we can use theshapeandratevalues from the current row indgamma().mutate(gamma_values = list(...))creates a new column where each cell is a vector of 30 Gamma values. Usinglist()is crucial here—without it, dplyr would try to collapse the vector into a single value, which isn't what we want.unnest_wider()takes the list column and splits it into 30 separate columns. Thenames_repairargument lets us customize the column names togamma_1,gamma_2, ...,gamma_30instead of the default auto-generated names.ungroup()turns off row-wise processing to make subsequent operations more efficient.
If you run head(df_with_gamma), you'll see your original columns plus the 30 new Gamma distribution columns, each populated with the correct values for that row's shape and rate.
This method scales really well—if you ever need more than 30 columns, just change 1:30 to the range you need, and the rest of the code stays the same.
内容的提问来源于stack exchange,提问作者spazznolo

