我试图使用单个条件语句使用dplyr更新R中的多个变量 . 我有一些工作代码(在下面发布),但我觉得效率很低,并且我确信必须有更好的方法 .
编辑:有关程序目的的描述 . 我们的想法是根据Species的值更新虹膜数据集,例如,如果Species ==“setosa”,则Species =“SETOSA”,Sepal.Length * = 1.5,Sepal.Width * = 0.5 .
library(dplyr)
library(tibble)
multi_update <- function(species , sepal.length , sepal.width , ret){
if ( species == "setosa") {
RET <- list(
Species = "SETOSA",
Sepal.Length = sepal.length * 1.5,
Sepal.Width = sepal.width * 0.5
)
} else if ( species == "versicolor") {
RET <- list(
Species = "VERSI",
Sepal.Length = sepal.length * 2,
Sepal.Width = sepal.width * 1.5
)
} else {
RET <- list(
Species = species,
Sepal.Length = sepal.length ,
Sepal.Width = sepal.width
)
}
return( RET[[ret]] )
}
iris %>%
tbl_df %>%
mutate( Sepal.Length = mapply(multi_update , Species , Sepal.Length , Sepal.Width , "Sepal.Length")) %>%
mutate( Sepal.Width = mapply(multi_update , Species , Sepal.Length , Sepal.Width , "Sepal.Width")) %>%
mutate( Species = mapply(multi_update , Species , Sepal.Length , Sepal.Width , "Species"))
1 回答
我们可以创建一个关键的val数据集,
join
与原始数据集和mutate
列