用str_c()或paste()命名或重命名R中的列表对象



我试图重命名一个列表对象,其中对象名称与str_c()或paste()放在一起,但似乎无法让它工作。我认为这是可能的,但我不知道怎么做。

# some data
params <- tibble(col1=c(1,2,3), col2=c("a", "b", "c"))
# create empty list
all_output <- list()
# append new df to list
all_output <- append(all_output, list("this_works_fine" = params))
# append new df to list using the concatenated string
all_output <- append(all_output, list(str_c("this_", "does_", "not_", "work") = params))

谢谢你的帮助!

使用setNames

append(all_output, setNames(list(params), str_c("this_", "does_", "not_", "work")))

与产出

$this_works_fine
# A tibble: 3 × 2
col1 col2 
<dbl> <chr>
1     1 a    
2     2 b    
3     3 c    
$this_does_not_work
# A tibble: 3 × 2
col1 col2 
<dbl> <chr>
1     1 a    
2     2 b    
3     3 c    

或用dplyr:=合成lst

append(all_output, lst(!!str_c("this_", "does_", "not_", "work") := params))

与产出

$this_works_fine
# A tibble: 3 × 2
col1 col2 
<dbl> <chr>
1     1 a    
2     2 b    
3     3 c    
$this_does_not_work
# A tibble: 3 × 2
col1 col2 
<dbl> <chr>
1     1 a    
2     2 b    
3     3 c