我有以下函数,我想将其应用于数据框的列:
ff <- function(w, epsi, df) {
res <- w*(max(df, na.rm = T) - min(df, na.rm=T)+2*epsi)+min(df, na.rm = T) - epsi
return(res)
}
该函数应使用参数 epsi
和 df
应用于 w
的每一列。该函数必须获取 w
的每个值,并将其乘以 df
相应列的最大值减去 df
该列的最小值,等等。
例如:
> w
# A tibble: 5 x 2
A B
<dbl> <dbl>
1 0.290 0.928
2 0.917 0.929
3 0.910 0.919
4 0.243 0.908
5 0.936 0.901
和df
是:
> df
# A tibble: 10 x 2
A B
<dbl> <dbl>
1 0.977 1.03
2 1.04 1.15
3 0.929 0.875
4 1.12 1.15
5 0.913 1.05
6 1.00 1.09
7 0.972 1.03
8 0.919 1.04
9 0.935 0.973
10 1.08 1.17
因此,对于 w
的第一个元素 0.290,该函数将 0.290 乘以 A
列中 df
的最大值 (1.12),等等。
如何使用 dplyr
将函数应用到 w
?
我尝试过:
w_new = w %>% mutate_each(ff(w,0.001, df))
但它不是一次只接受一列,而是尝试一次对所有列进行操作。
最佳答案
OP 表示希望使用 dplyr
基于此问题的解决方案因此我想使用 dplyr
提供答案。
在我们需要在另一个表中查找相应列(名称)的情况下,最好不要依赖列的顺序或使用特定的列名称。 quo_name
和quo
函数提供对 dplyr::mutate_all
范围内的列名称的访问功能。
使用 dplyr::mutate_all
的解决方案可以是:
# Re-wirte fucntion to accept the column name for df
ff <- function(x, epsi, colName) {
res <- x*(max(df[,colName], na.rm = TRUE) - min(df[,colName], na.rm=TRUE) +
2*epsi)+min(df[,colName], na.rm = TRUE) - epsi
return(res)
}
library(dplyr)
# The corresponding column names is passed to ff using quo_name(quo(.))
w %>% mutate_all(funs(ff(., 0.001, quo_name(quo(.)) )))
# A B
# 1 0.972610 1.149616
# 2 1.103653 1.149913
# 3 1.102190 1.146943
# 4 0.962787 1.143676
# 5 1.107624 1.141597
数据:
w <- read.table(text =
"A B
1 0.290 0.928
2 0.917 0.929
3 0.910 0.919
4 0.243 0.908
5 0.936 0.901",
header = TRUE)
df <- read.table(text =
"A B
1 0.977 1.03
2 1.04 1.15
3 0.929 0.875
4 1.12 1.15
5 0.913 1.05
6 1.00 1.09
7 0.972 1.03
8 0.919 1.04
9 0.935 0.973
10 1.08 1.17",
header = TRUE)
关于r - dplyr 使用多个参数的自定义函数分别在每一列进行变异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51569560/