![](/img/trans.png)
[英]How to use purrr modify_if with several functions with different arguments?
[英]How to use modify_if to divide each numeric column by another column?
我想將滿足條件的數據幀中的每一列除以同一數據幀中的一列
我相信它可以通過多種方式完成,但我覺得如果我可以使用專為此類工作設計的 purrr 包來完成它對我來說會更有效率。
例如,這有效
t <- iris %>%
modify_if(is.numeric, ~./2)
但這不
t <- iris %>%
modify_if(is.numeric, ~./Sepal.Length)
這導致錯誤
Error in .f(.x[[i]], ...) : object 'Sepal.Length' not found
我認為它希望我將 .y 指定為“Sepal.Length”,但我想不出正確的方法。
我對 modify2、imodify、map2 和 pmap 感到困惑
如果您能給我指出有關如何正確使用 purrr 的正確指南,我將不勝感激。 官方指南似乎對概念和直覺沒問題
但我正在努力將其應用於應用程序。 https://purrr.tidyverse.org/reference/modify.html
在這種情況下要使用modify_if
,我們可以這樣做
library(dplyr)
library(purrr)
iris %>% modify_if(is.numeric, ~./iris$Sepal.Length)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1 1 0.6862745 0.2745098 0.03921569 setosa
#2 1 0.6122449 0.2857143 0.04081633 setosa
#3 1 0.6808511 0.2765957 0.04255319 setosa
#4 1 0.6739130 0.3260870 0.04347826 setosa
#5 1 0.7200000 0.2800000 0.04000000 setosa
#6 1 0.7222222 0.3148148 0.07407407 setosa
#....
或者其他版本
iris %>% modify_if(is.numeric, function(x) x/.$Sepal.Length)
或者按照@Artem Sokolov 的建議
iris %>% modify_if(is.numeric, `/`, .$Sepal.Length)
另一種方法是使用mutate_if
,但是為此您需要重新排列@neilfws 提到的列
iris %>%
select(Sepal.Width, Petal.Length, Petal.Width, Species, Sepal.Length) %>%
mutate_if(is.numeric, ~./Sepal.Length)
最后使用基礎R
iris[] <- lapply(iris, function(x) if(is.numeric(x)) x/iris$Sepal.Length else x)
#OR
cols <- sapply(iris, is.numeric)
iris[cols] <- lapply(iris[cols], function(x) x/iris$Sepal.Length)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.