【问题标题】:How to turn tibble with comma a delimited column into tidy form如何将带逗号的 tibble 分隔列转换为整洁的形式
【发布时间】:2017-05-04 00:33:03
【问题描述】:

我有以下小标题:


df <- tibble::tribble(
  ~Sample_name, ~CRT,      ~SR,      ~`Bcells,DendriticCells,Macrophage`,
  "S1",          0.079,  0.592,      "0.077,0.483,0.555",
  "S2",          0.082,  0.549,      "0.075,0.268,0.120"
)

df
#> # A tibble: 2 × 4
#>   Sample_name   CRT    SR `Bcells,DendriticCells,Macrophage`
#>         <chr> <dbl> <dbl>                              <chr>
#> 1          S1 0.079 0.592                  0.077,0.483,0.555
#> 2          S2 0.082 0.549                  0.075,0.268,0.120

请注意,第三列以逗号分隔。如何将df 转换成这种整洁的形式:

Sample_name CRT   SR       Score     Celltype
S1          0.079 0.592    0.077     Bcells 
S1          0.079 0.592    0.483     DendriticCells
S1          0.079 0.592    0.555     Macrophage
S2          0.082 0.549    0.075     Bcells
S2          0.082 0.549    0.268     DendriticCells
S2          0.082 0.549    0.120     Macrophage

【问题讨论】:

  • 这看起来像是 CSV 没有正确读入。与其在事后尝试修复它,不如从一开始就弄清楚为什么它没有解决它会更容易。
  • 要修复读数,可能是cbind(df[-4], read.csv(text = paste(names(df)[4], paste(df[[4]], collapse = '\n'), sep = '\n'), header = TRUE)),然后您可以轻松地使用tidyr::gather 进行重塑。

标签: r dplyr tidyverse


【解决方案1】:

我们可以使用separate

df %>%
    separate(col = `Bcells,DendriticCells,Macrophage`,
             into = strsplit('Bcells,DendriticCells,Macrophage', ',')[[1]],
             sep = ',') %>%
    gather(Celltype, score, Bcells:Macrophage)
# # A tibble: 6 × 5
#   Sample_name   CRT    SR       Celltype score
# <chr> <dbl> <dbl>          <chr> <chr>
# 1          S1 0.079 0.592         Bcells 0.077
# 2          S2 0.082 0.549         Bcells 0.075
# 3          S1 0.079 0.592 DendriticCells 0.483
# 4          S2 0.082 0.549 DendriticCells 0.268
# 5          S1 0.079 0.592     Macrophage 0.555
# 6          S2 0.082 0.549     Macrophage 0.120

没有硬编码:

cn <- colnames(df)[ncol(df)]
df %>%
    separate_(col = cn, into = strsplit(cn, ',')[[1]],  sep = ',') %>%
    gather_('Celltype', 'score', strsplit(cn, ',')[[1]])

【讨论】:

  • 非常感谢。有没有办法不对Bcells,DendriticCells,Macrophage 进行硬编码?例如在您的代码中使用colnames(df)[ncol(df)]?以及gather中的Bcells:Macrophage,因为单元格类型的数量可以超过3,并且可以命名任何东西。
猜你喜欢
  • 2015-08-23
  • 1970-01-01
  • 2020-04-07
  • 2015-06-10
  • 2014-01-08
  • 1970-01-01
  • 2021-10-21
  • 2012-12-02
  • 2016-02-08
相关资源
最近更新 更多