根据其他列中的答案选择在数据框中创建新列

Creating a new column in a dataframe based on the answer choices in the other columns

我对如何根据其他各列中的字符组合来填充我的新列感到有点困惑。

这是我的原始数据框:

df <-  data.frame('Hispanic'=c("N", "Y", "N", "N"), 'Black'=c("Y", "N", "N", "Null"), 'Asian'=c("N", "Y", "N", "N"), 
                  'HN'=c("N", "N", "N", "N"), 'AN'=c("N", "N", "N", "Y"), 'White'=c("N", "Y", "N", "Null"), 
                  'NA'=c("N", "N", "Y", "Y"))

我想根据种族和种族的不同组合对新列中的变量进行编码。具体来说,我试图将这些因素分为黑人(非西班牙裔)、亚裔(非西班牙裔)、夏威夷原住民(非西班牙裔)、美国人 Indian/Alaska 原住民(非西班牙裔)、多种族(非西班牙裔)和西班牙裔。因此,只要记录的西班牙裔为“是”,填充的值就应该只是西班牙裔,但如果值为“否”,则应该详细说明选择了非西班牙裔(例如:黑人,新罕布什尔州)的单一种族,或者他们选择了多个种族种族它将是多种族和非西班牙裔(例如:多种族,新罕布什尔州)。

目标是获得类似于以下结果的内容:

df1 <- data.frame('Hispanic'=c("N", "Y", "N", "N"), 'Black'=c("Y", "N", "N", "Null"), 'Asian'=c("N", "Y", "N", "N"), 
                  'HN'=c("N", "N", "N", "N"), 'AN'=c("N", "N", "N", "Y"), 'White'=c("N", "Y", "N", "Null"), 
                  'NA'=c("N", "N", "Y", "Y"), 
                  'R_E'=c("Black, NH", "Hispanic", "Native American, NH", "Multi-racial, NH" )) 
df %>%
  rowid_to_column() %>%
  left_join(pivot_longer(.,-rowid) %>%
    group_by(rowid) %>%
    mutate(value = value == 'Y') %>%
    summarise(value = if(any(name =='Hispanic' & value))
      'Hispanic' else paste(if (sum(value)>1)
      'multiracial' else name[value], 'NH')))

      rowid Hispanic Black Asian HN AN White NA.          value
1     1        N     Y     N  N  N     N   N       Black NH
2     2        Y     N     Y  N  N     Y   N       Hispanic
3     3        N     N     N  N  N     N   Y         NA. NH
4     4        N  Null     N  N  Y  Null   Y multiracial NH