[英]How to Use forcats::fct_collapse in a Function Across Different Dataframes with Different Factor Levels
library(tidyverse)
library(forcats)
我有兩個簡單的數據框(底部的代碼),我想通過折疊“動物”列來創建一個新的重新編碼變量。 我通常用forcats::fct_collapse
來做這件事。 但是,我想創建一個函數來將 fct_collapse 應用於許多具有相同變量的不同數據幀,除了一些可能缺少一個或兩個因子級別。 例如,在這種情況下,Df2 缺少“Rhino”。
有沒有辦法可以更改代碼(使用 pkg:tidyverse),以便將缺少的因子類別返回為NA
? 在這個例子中,我知道它是“Rhino”,但在我的真實數據中可能還有其他缺失的級別。 除了forcats::fct_collapse
之外,我對其他選項持開放態度,但我想留在 tidyverse 的范圍內。
REC <- function(Df, Data){
Df %>%
mutate(NEW = fct_collapse(Data, One = c("Cat","Dog","Snake"),
Two = c("Elephant","Bird","Rhino")))
}
REC(Df1,Animal) - this works
REC(DF2,Animal) - this doesn't, it throws an error because of "Rhino"
樣本數據:
Animal <- c("Cat","Dog","Snake","Elephant","Bird","Rhino")
Code <- c(101,222,434,545,444,665)
Animal2 <- c("Cat","Dog","Snake","Elephant","Bird")
Code2 <- c(101,222,434,545,444)
Df1 <- data_frame(Code, Animal)
Df2 <- data_frame(Code2, Animal2) %> %rename(Animal = Animal2)
這是給你的一個想法。 我最初試圖在我的函數中有兩個參數。 一個用於數據框,另一個是包含動物名稱的列。 但這次嘗試失敗了。 我收到一條錯誤消息,說“mutate_impl(.data, dots) 中的錯誤: new
列的長度必須為 5(行數)或 1,而不是 6。” 所以我決定不在函數中使用列名; 我在我的功能中明確地說了Animal
。 然后,事情奏效了。 這個想法是創建一個缺少動物名稱的因子變量。 這是在factor()
和setdiff()
中完成的。 一旦我有了所有動物的名字,我就使用fct_collapse()
。
myfun <- function(mydf){
animals <- c("Cat", "Dog", "Snake", "Elephant", "Bird", "Rhino")
mydf %>%
mutate(new = factor(Animal, levels = c(unique(Animal), setdiff(animals, Animal))),
new = fct_collapse(new, One = c("Cat", "Dog", "Snake"),
Two = c("Elephant", "Bird", "Rhino"))) -> x
x}
> myfun(Df2)
# A tibble: 5 x 3
Code2 Animal new
<dbl> <chr> <fct>
1 101 Cat One
2 222 Dog One
3 434 Snake One
4 545 Elephant Two
5 444 Bird Two
> myfun(Df1)
# A tibble: 6 x 3
Code Animal new
<dbl> <chr> <fct>
1 101 Cat One
2 222 Dog One
3 434 Snake One
4 545 Elephant Two
5 444 Bird Two
6 665 Rhino Two
備忘:除了我有兩個參數之外,以下函數是相同的。 這是行不通的。 如果可以修改,請告訴我。
myfun2 <- function(mydf, mycol){
animals <- c("Cat", "Dog", "Snake", "Elephant", "Bird", "Rhino")
mydf %>%
mutate(new = factor(mycol, levels = c(unique(mycol), setdiff(animals, mycol))),
new = fct_collapse(new, One = c("Cat", "Dog", "Snake"),
Two = c("Elephant", "Bird", "Rhino"))) -> x
x}
> myfun2(Df2, Animal)
Error in mutate_impl(.data, dots) :
Column `new` must be length 5 (the number of rows) or one, not 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.