r - How to mutate several columns by column index rather than column name using across?
问题描述
Building on this questions:
R dplyr mutate on column index
dplyr: how to reference columns by column index rather than column name using mutate?
I want to mutate several columns using column indexes for both the source and the destination of the mutate like:
df <- tribble(~C1,~C2,~C3,1,2,3,4,5,6,7,8,9)
dfn <- df
dfn[,1:2] = dfn[,3] # like this in dplyr
df <- df %>% mutate(accross(.[[1:2]]) = .[[3]])
gives:
Fehler: Unerwartete(s) '=' in "df <- df %>% mutate(accross(.[[1:2]]) ="
Error: Unexpected '=' in "df <- df %>% mutate(accross(.[[1:2]]) ="
解决方案
The first argument of across can specify the columns to use and set and the second is the function to use to transform them. The second argument to across could alternately be function(x) .[[3]]
.
df %>% mutate(across(1:2, ~ cur_data()[[3]]))
giving:
# A tibble: 3 x 3
C1 C2 C3
<dbl> <dbl> <dbl>
1 3 3 3
2 6 6 6
3 9 9 9
These would also work and both run faster than the above with the last one being the fastest.
df %>% replace(1:2, .[[3]])
library(collapse)
df %>% ftransformv(1:2, function(x) .[[3]])
推荐阅读
- r - 在 R 中绘制时间序列,如何使用 12 小时时钟数据格式化 x 轴日期时间值
- google-cloud-platform - Terraform 销毁添加相同的资源
- javascript - React:如何在功能组件中创建状态依赖函数?
- c# - 如何避免 FluentValidation 中的重复外部调用
- react-native -
不起作用(视图位于通知选项卡上方) - css - 无法解析 'css-loader' - Webpack 入门错误
- reactjs - 浏览器刷新时购物车值重置
- python - 根据 if 问题更改 python for 循环
- rxjs - 如何通过管道 rx 运算符来组合片段数据?
- bash - OS X Bash 上的树命令