【问题标题】:Splitting Certain Rows in R into Multiple Rows? [duplicate]将R中的某些行拆分为多行? [复制]
【发布时间】:2020-10-23 11:29:39
【问题描述】:

有没有办法把这些数据转...

Month      Animal        Number    CodeName
8-9       cat             2         whiskers
3-4       cat|dog         1|4       whiskers|spot
10-11     elephant        5         trunks
7-8       cat|snake       3|2       whiskers|thomas
5-6       elephant|dog    0|7       trunks|spot

进入这个...

Month      Animal        Number    CodeName
8-9         cat           2         whiskers
3-4         cat           1         whiskers
3-4         dog           4         spot
10-11       elephant      5         trunks
7-8         cat           3         whiskers
7-8         snake         2         thomas
5-6         elephant      0         trunks
5-6         dog           7         spot

通过打断管道?

我将保持 Month 列相同,但 Animal、Number 和 CodeName 管道列将被拆分。

我为此尝试的最后一个代码是...

df %>% 单独的行(。,动物,数字,代号,转换=真)

但我收到“长度不兼容”的错误。

任何帮助将不胜感激

【问题讨论】:

  • 您能粘贴dput(df) 的输出,其中df 是数据框吗?您的 separate_rows 呼叫看起来正确。

标签: r string split tidyr


【解决方案1】:

您可以使用tidyr 中的separate_rows,但您必须正确地将sep 参数指定为sep = "\\|"。请注意,您必须转义 |,因为在正则表达式中它是一个特殊字符:

df <- read.table(text = "Month      Animal        Number    CodeName
8-9       cat             2         whiskers
3-4       cat|dog         1|4       whiskers|spot
10-11     elephant        5         trunks
7-8       cat|snake       3|2       whiskers|thomas
5-6       elephant|dog    0|7       trunks|spot", header = TRUE, stringsAsFactors = FALSE)

library(dplyr)
library(tidyr)

df %>% separate_rows(Animal, Number, CodeName, sep = "\\|")
  Month   Animal Number CodeName
1   8-9      cat      2 whiskers
2   3-4      cat      1 whiskers
3   3-4      dog      4     spot
4 10-11 elephant      5   trunks
5   7-8      cat      3 whiskers
6   7-8    snake      2   thomas
7   5-6 elephant      0   trunks
8   5-6      dog      7     spot

【讨论】:

    【解决方案2】:

    我们可以从splitstackshape使用cSplit

    library(splitstackshape)
    cSplit(df, c("Animal", "Number", "CodeName"), sep="|", "long")
    #  Month   Animal Number CodeName
    #1:   8-9      cat      2 whiskers
    #2:   3-4      cat      1 whiskers
    #3:   3-4      dog      4     spot
    #4: 10-11 elephant      5   trunks
    #5:   7-8      cat      3 whiskers
    #6:   7-8    snake      2   thomas
    #7:   5-6 elephant      0   trunks
    #8:   5-6      dog      7     spot
    

    数据

    df <- structure(list(Month = c("8-9", "3-4", "10-11", "7-8", "5-6"), 
        Animal = c("cat", "cat|dog", "elephant", "cat|snake", "elephant|dog"
        ), Number = c("2", "1|4", "5", "3|2", "0|7"), CodeName = c("whiskers", 
        "whiskers|spot", "trunks", "whiskers|thomas", "trunks|spot"
        )), class = "data.frame", row.names = c(NA, -5L))
    

    【讨论】:

      猜你喜欢
      • 2022-09-29
      • 1970-01-01
      • 2017-11-08
      • 2020-09-24
      • 1970-01-01
      • 2016-08-09
      • 2015-07-28
      • 2016-08-29
      • 1970-01-01
      相关资源
      最近更新 更多