This is mostly an aesthetic question, because I am getting the output I want. In the code below, I want names to be added to the dataframe along with the pmap statment so that I don't get a warning for the temporary names. What am I missing? Thanks!
num_covariates<-4
num_observations<-1000
betas<-c(1,2,3,4)
powers<-c(1,2,3,4)
sim_data<-pmap_dfc(.l = lst(grid=rep(num_observations,num_covariates),
power=powers),
.f = function(grid,power){((1:grid)^power)})%>%
set_names(paste0("x",1:num_covariates))
CodePudding user response:
One option to get rid of the message would be to set the names inside your function like so:
num_covariates <- 4
num_observations <- 1000
betas <- c(1, 2, 3, 4)
powers <- c(1, 2, 3, 4)
library(purrr)
library(tibble)
sim_data <- pmap_dfc(
.l = lst(
name = paste0("x", 1:num_covariates),
grid = rep(num_observations, num_covariates),
power = powers
),
.f = function(name, grid, power) {
setNames(tibble((1:grid)^power), name)
}
)
sim_data
#> # A tibble: 1,000 × 4
#> x1 x2 x3 x4
#> <dbl> <dbl> <dbl> <dbl>
#> 1 1 1 1 1
#> 2 2 4 8 16
#> 3 3 9 27 81
#> 4 4 16 64 256
#> 5 5 25 125 625
#> 6 6 36 216 1296
#> 7 7 49 343 2401
#> 8 8 64 512 4096
#> 9 9 81 729 6561
#> 10 10 100 1000 10000
#> # … with 990 more rows
CodePudding user response:
We can use some glue syntax availabe in the tidyverse packages:
library(tidyverse)
num_covariates<-4
num_observations<-1000
betas<-c(1,2,3,4)
powers<-c(1,2,3,4)
sim_data <- lst(grid=rep(num_observations,num_covariates),power=powers, n_names = 1:num_covariates) %>%
pmap_dfc(~ tibble('X{..3}' := ((1:..1)^..2)))
sim_data
#> # A tibble: 1,000 × 4
#> X1 X2 X3 X4
#> <dbl> <dbl> <dbl> <dbl>
#> 1 1 1 1 1
#> 2 2 4 8 16
#> 3 3 9 27 81
#> 4 4 16 64 256
#> 5 5 25 125 625
#> 6 6 36 216 1296
#> 7 7 49 343 2401
#> 8 8 64 512 4096
#> 9 9 81 729 6561
#> 10 10 100 1000 10000
#> # … with 990 more rows
#or
lst(grid=rep(num_observations,num_covariates),power=powers, n_names = 1:num_covariates) %>%
pmap_dfc(function(grid, power, n_names) tibble('X{n_names}' := ((1:grid)^power)))
#> # A tibble: 1,000 × 4
#> X1 X2 X3 X4
#> <dbl> <dbl> <dbl> <dbl>
#> 1 1 1 1 1
#> 2 2 4 8 16
#> 3 3 9 27 81
#> 4 4 16 64 256
#> 5 5 25 125 625
#> 6 6 36 216 1296
#> 7 7 49 343 2401
#> 8 8 64 512 4096
#> 9 9 81 729 6561
#> 10 10 100 1000 10000
#> # … with 990 more rows
Created on 2021-11-20 by the reprex package (v2.0.1)