【问题标题】:Subsetting a dataframe in R based on the elements in the columns根据列中的元素对 R 中的数据框进行子集化
【发布时间】:2021-10-13 01:25:56
【问题描述】:

我有一个数据框 ,它有 5 行和 6 列。

df <- data.frame(
  Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5"),
  category1 = c("a1", "", "b1", "a1", "c1"),
  category2 = c("", "", "", "", "a2"),
  category3 = c("a3", "", "b3", "", "a3"),
  category4 = c("", "", "", "", ""),
  category5 = c("", "", "a5", "b5", ""),
  stringsAsFactors = FALSE)

的每一列,我只需要保留出现在最高位置的元素,即

最后,删除这五列中没有元素的行,即

如何在 R 中以最简单的方式实现这一点?

【问题讨论】:

    标签: df category1 category5 r dataframe subset


    【解决方案1】:

    你可以使用 -

    library(dplyr)
    
    df %>%
      #Retain only the values that appear in topmost position
      mutate(across(starts_with('category'), ~replace(., -match(TRUE, . != ''), ''))) %>%
      #Drop the rows that have no element
      filter(if_any(starts_with('category'), ~. != ''))
    
    #  Hits category1 category2 category3 category4 category5
    #1 Hit1        a1                  a3                    
    #2 Hit3                                                a5
    #3 Hit5                  a2                              
    

    如果你想通过位置来做到这一点,你可以这样做 -

    df %>%
      mutate(across(2:6, ~replace(., -match(TRUE, . != ''), ''))) %>%
      filter(if_any(2:6, ~. != ''))
    

    【讨论】:

    • 谢谢!这完美地工作。我想知道是否有办法针对列名可能不同的情况调整您的方法。
    • 列名是什么? dplyr 中有很多函数可以用来选择列。 starts_withends_withmatchescontains 等。您也可以按位置选择列2:5
    • 好的。我想根据位置选择列将解决列名不同的问题。感谢您的澄清。
    • 能否请您展示如何根据列的位置选择列?我不知道语法
    • 您要选择的列的位置是什么?
    【解决方案2】:
    df %>% 
      mutate(across(.cols = -Hits, .fns = ~ifelse(row_number() == first(which(.!="")) | all(. == ""), ., ""))) %>% 
      filter(if_any(-Hits, ~.!=""))
    
      Hits category1 category2 category3 category4 category5
    1 Hit1        a1                  a3                    
    2 Hit3                                                a5
    3 Hit5                  a2                              
    

    【讨论】:

    • 感谢您的回答。这可行,但我想要空格而不是 。你能相应地编辑你的答案吗?
    • @AbhishekChowdhury 完成!
    • category4下还有
    • @AbhishekChowdhury 解决了!
    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 2013-08-15
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2021-12-03
    相关资源
    最近更新 更多