【问题标题】:R split column names with different occurrences of delimiter into strings and assign unique strings/string counts to a new dataframeR将具有不同分隔符出现的列名拆分为字符串,并将唯一的字符串/字符串计数分配给新的数据帧
【发布时间】:2021-09-20 03:58:36
【问题描述】:

我有一个大型数据框,其中包含这样的列名。我还没有尝试处理任何数据,只是列名。

strainA_1_batch1 strainA_2_bacth2 strainB_1_bacth1 strainC_1_bacth2 strainC_2_bacth2 strainD_a_1_bacth1 strainD_b_1_bacth1

我正在尝试制作一些像这样的统计表:

number of strains number of batches
5 2
Batch number of strains
batch1 4
batch2 2
strain number of samples
StrainA 2
StrainB 1
StrainC 2
StrainD_a 1
StrainD_b 1

我的第一个问题是如何处理strainD_astrainD_b 之类的事情,因为如果我在“_”上拆分,我将拆分部分菌株名称,并且不同的拆分数量会使访问信息更加困难。我通过指定拆分数量并从右侧开始拆分,在 python 中处理了类似的事情,但我不确定 R 等价物。

其次,也许我使用的搜索词是错误的,但我只找到了有关如何将一列分成多列的信息。我不需要拆分列,我只想从列名中获取信息。然后使用名称的每个部分的唯一出现来创建新的列或行名称,并计算每个名称的总出现次数。我对统计表的组织方式并不挑剔,只要信息准确即可

【问题讨论】:

    标签: r dataframe split strsplit


    【解决方案1】:

    我认为,如果您在“下划线、数字、下划线”处拆分,它会为您的上述陈述提供解决方案。这确实消除了数字和相关信息。这有关系吗?

    names <- c("strainA_1_batch1", "strainA_2_batch2", "strainB_1_batch1", "strainC_1_batch2", "strainC_2_batch2", 
               "strainD_a_1_batch1", "strainD_b_1_batch1")
    
    #split at the underscore, digit and underscore 
    splitList <- strsplit(names, "_\\d_")
    
    #convert to dataframe
    df <-data.frame(t(as.data.frame.list(splitList)))
    
    #clean up data.frame
    rownames(df)<-NULL
    names(df)<-c("Strain", "Batch")
    df
    
    #report
    table(df$Strain)
    table(df$Batch)
    

    另一种选择是将数字两侧的下划线替换为“”(或其他字符),然后在空格处分割。

    names<-gsub("_(\\d)_", " \\1 ", names)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-11
      • 2018-05-27
      • 2015-12-28
      • 2019-05-22
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多