添加后缀到一个新列

huangapple go评论62阅读模式
英文:

Add a suffix to a new column

问题

旨在在应用“left”函数后创建一个名为“bd_acct_left”的新列,其中包含后缀“_left”。
新DF列
Study
bd_acct
bd_acct_left
cc
cc_left
与其手动更改名称,我希望找到一种自动添加后缀的方法。

英文:

Aim to create a new column named that contains the suffix '_left' after function "left" has been applied
New DF columns
Study
bd_acct
bd_acct_left
cc
cc_left

Rather than changing names manually I would like to find a way of automating this addition of a suffix

study <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
bd_acct <- c(57,66,72,24,76,98,56,32,43,250000,87,34,0,0,67)
cc <- c(1,2,3,5,74,3,5,6,5,3,5,6,7,4,1)
trial_A <- data.frame(study, bd_acct,cc) 

left <- function(x, na.rm = FALSE) (quantile(x,0.25) - 1.5*IQR(x))
trial_A %>% mutate_at(c("bd_acct", "cc"), left)


答案1

得分: 2

使用 `dplyr::mutate` 结合 `across()` 和 `.names` 参数:

库(dplyr)
trial_A %>%
mutate(across(bd_acct:cc, left,
.names = "{.col}_left"))

输出:

study bd_acct cc bd_acct_left cc_left

1 1 57 1 -28.5 -0.75

2 2 66 2 -28.5 -0.75

3 3 72 3 -28.5 -0.75

.....


<details>
<summary>英文:</summary>

Use `dplyr::mutate` with `across()` and the `.names` argument:

library(dplyr)
trial_A %>%
mutate(across(bd_acct:cc, left,
.names = "{.col}_left"))

Output:

study bd_acct cc bd_acct_left cc_left

1 1 57 1 -28.5 -0.75

2 2 66 2 -28.5 -0.75

3 3 72 3 -28.5 -0.75

.....


</details>



huangapple
  • 本文由 发表于 2023年3月7日 21:40:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定