在 purrr::pmap_dfc() 中为临时名称设置警告前的名称

Set names before warning for temporary names in purrr::pmap_dfc()

这主要是一个美学问题,因为我得到了我想要的输出。在下面的代码中,我希望将名称与 pmap 语句一起添加到数据框中,这样我就不会收到有关临时名称的警告。我错过了什么?谢谢!

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))

消除该消息的一种方法是在您的函数中设置名称,如下所示:

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

我们可以使用 tidyverse 包中可用的一些粘合语法:

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

reprex package (v2.0.1)

于 2021-11-20 创建