[英]Using If to select dataframe by name from list in R
In R: I have a list of 3 dataframes (Book1, Book2, Book3), list named dflist4. 在R中:我有3个数据帧的列表(Book1,Book2,Book3),列表名为dflist4。 I have a code I want to apply to each dataframe separately in the list because the value of maxm is different for each dataframe.
我有一个代码想要分别应用于列表中的每个数据框,因为maxm的值对于每个数据框都不同。 I wrote it, and it works, but only when Book1, Book2, and Book3 are all equally sized dataframes.
我编写了它,并且它起作用了,但是仅当Book1,Book2和Book3的大小均相等时才是如此。 When they are not equally sized, the code will not run (error: ops.dataframe == only defined for equally-sized dataframes).
当它们的大小不相等时,代码将不会运行(错误:ops.dataframe ==仅为大小相等的数据帧定义)。 When I change the == to = , i get that it is not logical.
当我将==更改为=时,我发现这是不合逻辑的。 Can anyone please give a suggestion as to how to select the dataframes from the list based on their names no matter the size of the dataframe?
任何人都可以提出建议,无论数据帧的大小如何,如何根据其名称从列表中选择数据帧?
Code here: 代码在这里:
eggplant<-function(x){
(if((x == (dflist4[["Book1"]])){
maxm = 3;
x %>% mutate(Col4 = (x[,3])/maxm);
})
(if((x == dflist4[["Book2"]])){
maxm = 2;
x %>% mutate(Col4 = (x[,3])/maxm);
})
(if((x == dflist4[["Book3"]])){
maxm = 1;
x %>% mutate(Col4 = (x[,3])/maxm);
})
}
test<-lapply(dflist4, eggplant)
Following up from my comments above, I assume the third column in Book1
, Book2
, Book3
is called Col3
. 根据上面的评论,我假设
Book1
, Book2
, Book3
的第三列称为Col3
。
You can use purrr::map2
您可以使用
purrr::map2
library(tidyverse)
purrr::map2(dflist4, c(3, 2, 1), function(df, maxm) df %>% mutate(Col4 = Col3 / maxm))
As you don't provide sample data, here is an mtcars
-based example 由于您不提供示例数据,因此以下是基于
mtcars
的示例
purrr::map2(list(mtcars[1:3, ], mtcars[1:3, ]), c(10, 100), function(df, maxm)
df %>% mutate(mpg.new = mpg / maxm))
#[[1]]
# mpg cyl disp hp drat wt qsec vs am gear carb mpg.new
#1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 2.10
#2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 2.10
#3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 2.28
#
#[[2]]
# mpg cyl disp hp drat wt qsec vs am gear carb mpg.new
#1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 0.210
#2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 0.210
#3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 0.228
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.