簡體   English   中英

如何根據另一個數據框的列名重命名因子?

[英]How can I rename factors based on the column names of another data frame?

我在一個 dataframe 持有科目的專欄中:

sub <- c("A", "A", "B", "C", "C", "C", "D", "E", "F", "F")
subjects <- data.frame(sub)

我有另一個包含主題列的數據框(其中主題僅在一列中找到):

one <- c("A", "C", "F")
two <- c("B", "D", NA)
three <- c("E", NA, NA)
newsubjects <- data.frame(one, two, three)

我想將第一個 dataframe 中的主題重命名為第二個 dataframe 中與該主題對應的列名稱。

因此,例如,我希望將第一個 dataframe 中的 A、C 和 F 科目重命名為“一”。 手動執行此操作會花費很長時間,因此我希望有一種方法可以使用第二個數據框中的列來執行此操作。

我用 forcats::fct_recode 和 levels 嘗試了很多東西,但沒有任何效果,因為我沒有正確使用這些功能。 例如 IIRC 我的嘗試之一看起來像這樣:

subjects %>%
      mutate(new_var = forcats::fct_recode(sub,
            !!! setNames(as.character(subjects$sub), newsubjects$one)))

我知道這是完全錯誤的。 部分問題是我很難以返回相關搜索結果的方式闡明我的問題。 感謝您提供的任何幫助,我很感激。

使用purrr::map() ,從newsubjects派生一個列表配對列名和值。 然后在forcats::fct_collapse()中解壓以重新編碼subjects中的值。

library(purrr)
library(forcats)

new_ids <- map(newsubjects, ~ .x[!is.na(.x)])

subjects$sub <- fct_collapse(subjects$sub, !!!new_ids)

subjects
     sub
1    one
2    one
3    two
4    one
5    one
6    one
7    two
8  three
9    one
10   one

如果你 reshape newsubjects的時間更長,你可以加入這兩個表:

library(tidyverse)
subjects %>%
  left_join(newsubjects %>% 
            pivot_longer(everything(), names_to = "new_sub", values_to = "sub")) 

Joining, by = "sub"
   sub new_sub
1    A     one
2    A     one
3    B     two
4    C     one
5    C     one
6    C     one
7    D     two
8    E   three
9    F     one
10   F     one

在一、二、三等長度的基礎上,您還可以創建一個查找

library(dplyr)

sub <- c("A", "A", "B", "C", "C", "C", "D", "E", "F", "F")
subjects <- data.frame(sub)

one <- c("A", "C", "F")
two <- c("B", "D", NA)
three <- c("E", NA, NA)

additions <- c(one, two, three)

lookup <- data.frame(
  sub = additions %>% unlist(), 
  value = rep(1:length(additions), each=length(additions[[1]])))

subjects %>% inner_join(lookup) %>% select(value)

在基地 R 中:

gsub("\\d", "", names(unlist(newsubjects))[match(subjects$sub, unlist(newsubjects))])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM