假设我有一组列,在我的示例中名为Intercept, 1, 2,3以及一组系数,名为c0through c3。
xs<-seq(.1,1,.1)
X <- cbind(Intercept=1, "1"=xs, "2"=xs^2, "3"=xs^3)
coefs <- c(c0=10, c1=2, c2=.5, c3=-1)
Run Code Online (Sandbox Code Playgroud)
我想将 X 的每一列乘以相应的系数。
sweep(
X, # x: the data array
2, # MARGIN: 2, to sweep across rows
coefs, # STATS: just the array of coefficients
`*`) # FUN: the function to use is multiplication
Run Code Online (Sandbox Code Playgroud)
这给出了我想要的。
但是,如果我的数据为 tibble ( tidyX <- as_tibble(X)),那么执行此操作的简洁方法是什么?
tidyX %>% ... ?
Run Code Online (Sandbox Code Playgroud)
这看起来很简单,我想它dplyr::rowwise()可能涉及,但我没有看到这样做的惯用方法。
啊,就在我终于发帖的时候,我找到了答案。
tidyX %>%
rowwise() %>%
mutate(across() * coefs)
Run Code Online (Sandbox Code Playgroud)
我仍然发现这种语法不直观,但这正是我正在寻找的。
这是使用旋转的另一种方法:
library(dplyr)
library(tidyr)
coefs <- c(c0=10, c1=2, c2=.5, c3=-1)
X %>%
as_tibble() %>%
mutate(row = row_number()) %>%
pivot_longer(
-row
) %>%
mutate(value = value*coefs) %>%
pivot_wider(
names_from = name,
values_from = value
) %>%
select(-row)
Run Code Online (Sandbox Code Playgroud)
Intercept `1` `2` `3`
<dbl> <dbl> <dbl> <dbl>
1 10 0.2 0.005 -0.001
2 10 0.4 0.02 -0.008
3 10 0.6 0.045 -0.027
4 10 0.8 0.08 -0.064
5 10 1 0.125 -0.125
6 10 1.2 0.18 -0.216
7 10 1.4 0.245 -0.343
8 10 1.6 0.32 -0.512
9 10 1.8 0.405 -0.729
10 10 2 0.5 -1
Run Code Online (Sandbox Code Playgroud)