[英]Using If to select dataframe by name from list in R
在R中:我有3個數據幀的列表(Book1,Book2,Book3),列表名為dflist4。 我有一個代碼想要分別應用於列表中的每個數據框,因為maxm的值對於每個數據框都不同。 我編寫了它,並且它起作用了,但是僅當Book1,Book2和Book3的大小均相等時才是如此。 當它們的大小不相等時,代碼將不會運行(錯誤:ops.dataframe ==僅為大小相等的數據幀定義)。 當我將==更改為=時,我發現這是不合邏輯的。 任何人都可以提出建議,無論數據幀的大小如何,如何根據其名稱從列表中選擇數據幀?
代碼在這里:
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)
根據上面的評論,我假設Book1
, Book2
, Book3
的第三列稱為Col3
。
您可以使用purrr::map2
library(tidyverse)
purrr::map2(dflist4, c(3, 2, 1), function(df, maxm) df %>% mutate(Col4 = Col3 / maxm))
由於您不提供示例數據,因此以下是基於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.