【问题标题】:How can I split R dataframe rows into multiple rows based on a condition?如何根据条件将 R 数据框行拆分为多行?
【发布时间】:2020-10-23 10:29:08
【问题描述】:

如果我的数据类似于这样:

  Variable 1   Variable 2   Variable 3
1   Red|Blue      0|1          1|0
2   Blue|Red      1|0          0|1
3   Green|Red     0|1          1|0
4   Yellow|Blue   1|0          0|1

我可以根据“|”使用什么来分隔?像这样的:

 Variable 1   Variable 2   Variable 3
1   Red           0            1
2   Blue          1            0
3   Blue          1            0
4   Red           0            1
5   Green         0            1
6   Red           1            0
7   Yellow        1            0
8   Blue          0            1

【问题讨论】:

  • 查看tidyr::separate_rows()。例如,separate_rows(df, everything(), sep = "\\|")

标签: r string split tidyr


【解决方案1】:

我们也可以使用splitstackshape中的cSplit

library(splitstackshape)
cSplit(df1, c("Variable1", "Variable2", "Variable3"), sep="|", "long")
#   Variable1 Variable2 Variable3
#1:       Red         0         1
#2:      Blue         1         0
#3:      Blue         1         0
#4:       Red         0         1
#5:     Green         0         1
#6:       Red         1         0
#7:    Yellow         1         0
#8:      Blue         0         1

数据

df1 <- structure(list(Variable1 = c("Red|Blue", "Blue|Red", "Green|Red", 
"Yellow|Blue"), Variable2 = c("0|1", "1|0", "0|1", "1|0"), Variable3 = c("1|0", 
"0|1", "1|0", "0|1")), class = "data.frame", row.names = c("1", 
"2", "3", "4"))

【讨论】:

    【解决方案2】:

    您可以使用separate_rows

    > df %>% 
       separate_rows(., Variable1, Variable2, Variable3, convert = TRUE)
    # A tibble: 8 x 3
      Variable1 Variable2 Variable3
      <chr>         <int>     <int>
    1 Red               0         1
    2 Blue              1         0
    3 Blue              1         0
    4 Red               0         1
    5 Green             0         1
    6 Red               1         0
    7 Yellow            1         0
    8 Blue              0         1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多