【问题标题】:Subset Data Frame Rows by value in row.names in R按 R 中 row.names 中的值对数据框行进行子集
【发布时间】:2020-12-17 04:51:58
【问题描述】:

我见过这个Subsetting a data frame based on a logical condition on a subset of rows 和那个https://statisticsglobe.com/filter-data-frame-rows-by-logical-condition-in-r

我想根据 row.names 中的特定值对 data.frame 进行子集化。

data <- data.frame(x1 = c(3, 7, 1, 8, 5),                    # Create example data
                   x2 = letters[1:5],
                   group = c("ga1", "ga2", "gb1", "gc3", "gb1"))
data                                                         # Print example data
# x1 x2 group
#  3  a    ga1
#  7  b    ga2
#  1  c    gb1
#  8  d    gc3
#  5  e    gb1

我想根据组对data 进行子集化。一个子集应该是在其组中包含 a 的行,在其组中包含 b 的行和在其组中包含 c 的行。可能是grepl

结果应该是这样的

data.a                                                       
# x1 x2 group
#  3  a    ga1
#  7  b    ga2

data.b                                                      
# x1 x2 group
#  1  c    gb1
#  5  e    gb1

data.c
#  8  d    gc3

我会对如何对这些输出示例之一进行子集化感兴趣,或者循环也可以工作。

我从这里修改了示例https://statisticsglobe.com/filter-data-frame-rows-by-logical-condition-in-r

【问题讨论】:

  • 您的问题已完全按照您的要求得到回答。好问题。

标签: r dataframe row subset


【解决方案1】:

好问题。此解决方案使用与请求密切匹配的输入和输出:"I want to subset data according to group. One subset should be the rows containing a in their group, one containing b in their group and one c. Maybe something with grepl?"

下面的代码使用提供的数据框(命名数据),并使用 grep() 和分组子集。

代码:

ga <- grep("ga", data$group)   # seperate the data by group type
gb <- grep("gb", data$group)   
gc <- grep("gc", data$group) 

ga1 <- data[ga,]                     # subset ga
gb1 <- data[gb,]                     # subset gb
gc1 <- data[gc,]                     # subset gc

print(ga1)
print(gb1)
print(gc1)

使用了 Windows 和 Jupyter Lab。这里的输出与上面显示的输出非常匹配。

链接显示的输出:link1

【讨论】:

    【解决方案2】:

    我们可以在tidyverse 中使用group_splitstr_remove

    library(dplyr)
    library(stringr)
    data %>% 
        group_split(grp = str_remove(group, "\\d+$"), .keep = FALSE)
    

    【讨论】:

      【解决方案3】:

      提取要拆分的数据:

      sub('\\d+', '', data$group)
      #[1] "ga" "ga" "gb" "gc" "gb"
      

      并使用split中的上述内容将数据分组。

      new_data <- split(data, sub('\\d+', '', data$group))
      new_data
      #$ga
      #  x1 x2 group
      #1  3  a   ga1
      #2  7  b   ga2
      
      #$gb
      #  x1 x2 group
      #3  1  c   gb1
      #5  5  e   gb1
      
      #$gc
      #  x1 x2 group
      #4  8  d   gc3
      

      不过,最好将数据保存在一个列表中,如果您想为每个组设置单独的数据框,您可以使用list2env

      list2env(new_data, .GlobalEnv)
      

      【讨论】:

        猜你喜欢
        • 2021-12-04
        • 2021-09-16
        • 1970-01-01
        • 2014-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-16
        相关资源
        最近更新 更多