【问题标题】:Use substrings of column names in across in R在 R 中的 across 中使用列名的子字符串
【发布时间】:2022-12-03 21:16:32
【问题描述】:

I have the following tibble:

df <- tibble(
  x = c(5, 5),
  Column_1 = c(0.5, 0.5),
  Column_2 = c(0.75, 0.75))

I would like to create two new columns, which are the product of column x and Column_1 and x and Column_2 respectively. These columns should be named NewColumn_1 and NewColumn_2.

I tried the following code:

df <- mutate(df,
  across(starts_with(\"Column_\"),
              function(y) y * x,
              .names = paste0(\"NewColumn\", gsub(\"Column_\", \"\", \"{.col}\"))
        ))

However, this resulted in the following table:

x Column_1 Column_2 NewColumnColumn_1 NewColumnColumn_2
5 0.5 0.75 2.5 3.75
5 0.5 0.75 2.5 3.75

The resulting columns are now named NewColumnColumn_1 and NewColumnColumn_2. Somehow creating a substring with gsub did not work. My desired output is:

x Column_1 Column_2 NewColumn_1 NewColumn_2
5 0.5 0.75 2.5 3.75
5 0.5 0.75 2.5 3.75

Any ideas how I can elegantly solve this problem? In reality, the number of columns is variable, so I cannot hardcode 1 and 2 into my script.

  • Why dont you just paste New instead of NewColumn?

标签: r gsub across mutate r-glue


【解决方案1】:
猜你喜欢
  • 2021-03-01
  • 2021-12-11
  • 2015-03-06
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
  • 2015-06-14
  • 2021-02-05
  • 1970-01-01
相关资源
最近更新 更多