管道R代码中的setnames [英] setnames in pipeline R code

查看:545
本文介绍了管道R代码中的setnames的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在管道代码的末尾设置列表元素的名称.

I was wondering if it was possible to set the names of elements of a list at the end of a pipeline code.

  data <- input_vars %>% 
    purrr::map(get_data)

  names(data) <- input_vars

目前,我将一串变量传递到一个函数中,该函数检索数据帧列表.不幸的是,该列表没有自动包含命名元素,但是我之后手动"添加了它们.为了提高可读性,我想做些以下事情

Currently I pass a string of variables into a function which retrieves a list of dataframes. Unfortunately this list does not automatically have named elements, but I add them "manually" afterwards. In order to improve readability I would like to have something as follows

  data <- input_vars%>% 
    purrr::map(get_comm_data) %>%
    setnames(input_vars)

但是,这给了我以下错误: setnames(.,input_vars)中的错误:x不是data.table或data.frame

However, this gives me the following error: Error in setnames(., input_vars) : x is not a data.table or data.frame

有人对此有一个优雅的解决方案吗?

Does someone have an elegant solution to this?

感谢您的帮助!

推荐答案

要设置管道中对象的名称,请使用setNamespurrr::set_names

To set names of an object in a pipeline, use setNames or purrr::set_names

1:3 %>%
  purrr::map(~ rnorm(5, .x)) %>%
  purrr::set_names(paste0('V', 1:3))
#> $V1
#> [1] 1.4101568 2.0189473 1.0042691 1.4561920 0.8683156
#> 
#> $V2
#> [1] 2.0577889 2.4805984 1.4519552 0.9438844 0.4097615
#> 
#> $V3
#> [1] 0.4065113 4.0044538 2.8644864 2.4632038 4.0581380

1:3 %>%
  purrr::map(~ rnorm(5, .x)) %>%
  setNames(paste0('V', 1:3))
#> $V1
#> [1] 0.52503624 0.69096126 0.08765667 0.97904520 0.29317579
#> 
#> $V2
#> [1] 2.561081 1.535689 1.681768 2.739482 1.842833
#> 
#> $V3
#> [1] 2.619798 1.341227 2.897310 2.860252 1.664778

使用purrr::map,您还可以将input_vars命名为map保留名称.

With purrr::map you could also name your input_vars as map keep names.

c(V1 = 1, V2 = 2, V3 = 3) %>%
  purrr::map(~ rnorm(5, .x))
#> $V1
#> [1]  1.74474389  1.69347668 -1.03898393  0.09779935  0.95341349
#> 
#> $V2
#> [1] 1.5993430 0.8684279 1.6690726 2.9890697 3.8602331
#> 
#> $V3
#> [1] 3.453653 3.392207 2.734143 1.256568 3.692433

这篇关于管道R代码中的setnames的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆