【问题标题】:subsetting a dataframe by comparing columns通过比较列对数据框进行子集化
【发布时间】:2018-06-13 15:15:31
【问题描述】:

我想使用 R 来根据一些文件的值合并一些文件 参数。我正在使用以下 csv 文件

ls table.csv  
filename,type,rep,category,param
file1,1,4,A,1
file2,3,1,B,1
file3,2,1,A,2
file4,1,1,C,3
file5,1,1,C,2
file6,2,2,D,1
file7,3,1,C,2
file8,3,1,B,3
file9,3,1,B,3
file10,1,4,A,1
file11,1,1,B,1

ta <- readr::read_csv("table.csv")
Parsed with column specification:
cols(
filename = col_character(),
type = col_integer(),
rep = col_integer(),
category = col_character(),
param = col_integer()
)

我想合并具有相同值的文件 ta$type、ta$rep 和 ta$category(ta$param 无关)。

所以我会合并:file1, file10 [1,4,A] file2, file8, file9 [3,1,B] 文件 4、文件 5 [1,1,C] 文件 3 [2,1,A]、文件 6 [2,2,D]、文件 7 [3,1,C] 和 file11[1,1,B] 不会与任何其他文件合并。

有没有人知道如何做到这一点?谢谢!

【问题讨论】:

  • 你的预期输出是什么?
  • 三个新的拼接文件(file1+file10、file2+file8+file9和file4+file5)
  • cmets 不清楚
  • 我想得到三个输出文件,newfile1
  • 您的问题将极大地受益于您引用代码或数据结构的一些额外格式,例如:fileX [a, b, c]。这将使人们更容易理解您的问题和帮助。

标签: r dataframe subset


【解决方案1】:

一个选项是在列 (type, rep, category) 上使用 dplyr::group_by,然后在 summarise 上使用 paste0 和 collapse="+" 参数。解决方案如下:

library(readr)

library(dplyr)

ta <- readr::read_csv("table.csv")

ta %>% group_by(type, rep, category) %>%
  summarise(file = paste0(filename, collapse="+"))


# # A tibble: 7 x 4
# # Groups: type, rep [?]
#    type   rep category file             
#   <int> <int> <chr>    <chr>            
# 1     1     1 B        file11           
# 2     1     1 C        file4+file5      
# 3     1     4 A        file1+file10     
# 4     2     1 A        file3            
# 5     2     2 D        file6            
# 6     3     1 B        file2+file8+file9
# 7     3     1 C        file7

【讨论】:

    猜你喜欢
    • 2012-10-27
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 2016-07-02
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多