r - 依次遍历 R 中的两个列表
问题描述
我有两个看起来像这样的 df
library(tidyverse)
iris <- iris%>% mutate_at((1:4),~.+2)
iris2 <- iris
names(iris2)<-sub(".", "_", names(iris2), fixed = TRUE)
我的目标是减少iris
高于相应变量最大值的变量值iris2
,以匹配 中的最大值iris2
。
我写了一个函数来做到这一点。
max(iris$Sepal.Length)
[1] 9.9
max(iris2$Sepal_Length)
[1] 7.9
# i want every value of iris that is >= to max value of iris2 to be equal to the max value of iris 2.
# my function:
fixmax<- function(data,data2,var1,var2) {
data<- data %>%
mutate("{var1}" := ifelse(get(var1)>=max(data2[[var2]],na.rm = T),
max(data2[[var2]],na.rm = T),get(var1)))
return(data)
}
# apply my function to a variable
tst_iris <- fixmax(iris,iris2,"Sepal.Length","Sepal_Length")
max(tst_iris$Sepal.Length)
7.9 # it works!
我面临的挑战是我想在两个变量列表上依次Sepal.Length
迭代我的函数 - 即with Sepal_Length
,Sepal.Width
withSepal_Width
等。
有谁知道我该怎么做?
我尝试使用Map
,但我做错了什么。
lst1 <- names(iris[,1:4])
lst2 <- names(iris2[,1:4])
final_iris<- Map(fixmax,iris, iris2,lst1,lst2)
我的目标是获得一个 df( final_iris
),其中每个变量都已使用fixmax
. 我知道我可以通过像这样在每个变量上运行我的函数来做到这一点。
final_iris <- iris
final_iris <- fixmax(final_iris,iris2,"Sepal.Length","Sepal_Length")
final_iris <- fixmax(final_iris,iris2,"Sepal.Width","Sepal_Width")
final_iris <- fixmax(final_iris,iris2,"Petal.Length","Petal_Length")
final_iris <- fixmax(final_iris,iris2,"Petal.Width","Petal_Width")
但在实际数据中,我必须运行此操作数十次,并且我希望能够按顺序循环我的函数。有谁知道我如何按顺序循环我的fixmax
?lst1
lst2
解决方案
您可以利用内置于R
. 如果数据框具有相同的列/变量排序,则使用映射到两个数据框的函数mapply
或purrr::map2
将逐列迭代,而无需指定列名。
给定两个输入数据帧 (df_small
和df_big
),步骤是:
- 计算每列的最大值
df_small
以创建df_small_max
- 将函数应用于using
pmin
的每一列df_big
和每个值(或者如果您更喜欢映射)df_small_max
mapply
purr::map2_dfc
tidyverse
#set up fake data
df_small <- iris[,1:4]
df_big <- df_small + 2
# find max of each col in df_small
df_small_max <- sapply(df_small, max)
# replace values of df_big which are larger than df_small_max
df_big_fixed <- mapply(pmin, df_big, df_small_max)
# sanity check -- Note the change in Sepal.Width
df_small_max
#> Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 7.9 4.4 6.9 2.5
head(df_big, 3)
#> Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 1 7.1 5.5 3.4 2.2
#> 2 6.9 5.0 3.4 2.2
#> 3 6.7 5.2 3.3 2.2
head(df_big_fixed, 3)
#> Sepal.Length Sepal.Width Petal.Length Petal.Width
#> [1,] 7.1 4.4 3.4 2.2
#> [2,] 6.9 4.4 3.4 2.2
#> [3,] 6.7 4.4 3.3 2.2
由reprex 包于 2021-07-31 创建 (v2.0.0 )
推荐阅读
- python - 在 pandas.DataFrame 中查找下一个值组的行号
- javascript - 分离()然后附加()
- tsql - 通过更新同一列实现滞后功能
- c++ - 无法从发布者和订阅者节点可视化 Rviz (ROS) 中的 PointCloud
- jenkins - 使用共享库时出现 MissingMethodException
- google-cloud-firestore - 使用 Google 帐户在桌面应用程序中进行身份验证
- python - 添加零的列和原始值
- macos - 如何在 mac 上安装 dylib 文件?
- ruby-on-rails - Rails 5按belongs_to关联分组
- angular - 将可发布库导入另一个库失败 Angular