传递一个函数中新列的列名,而无需花序?

发布于 2025-02-10 07:50:40 字数 1137 浏览 2 评论 0原文

我用tidyeval为这个问题做了解决方案,是否有基本R方法?

library(dplyr)

new_col <- function(df, col_name, col_vals){
  df |>
    cbind(temp_name = col_vals) |>
    rename({{col_name}} := temp_name)
}

sleep %>% 
  new_col(sample, "sample1") |>
  new_col(condition, "condition2") |>
  head()
#>   extra group ID  sample  condition
#> 1   0.7     1  1 sample1 condition2
#> 2  -1.6     1  2 sample1 condition2
#> 3  -0.2     1  3 sample1 condition2
#> 4  -1.2     1  4 sample1 condition2
#> 5  -0.1     1  5 sample1 condition2
#> 6   3.4     1  6 sample1 condition2

“ https://reprex.tidyverse.org”创建2022-06-24

tidyeval 尚不清楚的概念。此答案也使用{{}}}和此答案使用Enquo()。我的解决方案还需要:=

理想情况下,我想将元数据的向量(例如,在数据框中)映射到数据范围/对象的匹配列表。

I have worked a solution to this problem with tidyeval, is there a base R method?

library(dplyr)

new_col <- function(df, col_name, col_vals){
  df |>
    cbind(temp_name = col_vals) |>
    rename({{col_name}} := temp_name)
}

sleep %>% 
  new_col(sample, "sample1") |>
  new_col(condition, "condition2") |>
  head()
#>   extra group ID  sample  condition
#> 1   0.7     1  1 sample1 condition2
#> 2  -1.6     1  2 sample1 condition2
#> 3  -0.2     1  3 sample1 condition2
#> 4  -1.2     1  4 sample1 condition2
#> 5  -0.1     1  5 sample1 condition2
#> 6   3.4     1  6 sample1 condition2

Created on 2022-06-24 by the reprex package (v2.0.1)

This seems indirect and depends on tidyeval concepts that are less known. This answer also uses {{}} and this answer uses enquo(). My solution also needs :=.

Ideally, I want to map vectors of metadata (say, in a dataframe) to a matching list of dataframes/objects.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

许久 2025-02-17 07:50:40

基础r中,我们可以使用depars/替代

new_col <- function(df, col_name, col_vals){
  cn <- deparse(substitute(col_name))
  df[[cn]] <- col_vals  
   df
}

- 测试

 sleep %>% 
+   new_col(sample, "sample1") |>
+   new_col(condition, "condition2") |>
+   head()
  extra group ID  sample  condition
1   0.7     1  1 sample1 condition2
2  -1.6     1  2 sample1 condition2
3  -0.2     1  3 sample1 condition2
4  -1.2     1  4 sample1 condition2
5  -0.1     1  5 sample1 condition2
6   3.4     1  6 sample1 condition2

In base R, we can use deparse/substitute

new_col <- function(df, col_name, col_vals){
  cn <- deparse(substitute(col_name))
  df[[cn]] <- col_vals  
   df
}

-testing

 sleep %>% 
+   new_col(sample, "sample1") |>
+   new_col(condition, "condition2") |>
+   head()
  extra group ID  sample  condition
1   0.7     1  1 sample1 condition2
2  -1.6     1  2 sample1 condition2
3  -0.2     1  3 sample1 condition2
4  -1.2     1  4 sample1 condition2
5  -0.1     1  5 sample1 condition2
6   3.4     1  6 sample1 condition2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文