将一列中的多个值拆分为多个行R

时间:2017-06-06 23:04:51

标签: r dplyr tidyr

我有一个数据框,大部分是每行一个观察。但是,某些行具有多个值:

# A tibble: 3 x 2
          `number`   abilities
             <dbl>       <chr>
1               51       b1261
2               57        d710
3               57 b1301; d550

structure(list(`number` = c(51, 57, 57), abilities = c("b1261", 
"d710", "b1301; d550")), .Names = c("number", "abilities"
), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"
))

我想得到以下内容:

# A tibble: 3 x 2
          `number`   abilities
             <dbl>       <chr>
1               51       b1261
2               57        d710
3               57        d550
4               57       b1301

直截了当地分开了;但我不确定如何轻松添加新行,尤其是当能力可能包含2个以上的值时。

这与:R semicolon delimited a column into rows非常相似,但不需要删除重复项

3 个答案:

答案 0 :(得分:17)

separate_rows中的tidyr功能可以做到这一点:

library(tidyr)
## The ";\\s+" means that the separator is a ";" followed by one or more spaces
separate_rows(df,abilities,sep=";\\s+")
  number abilities
   <dbl>     <chr>
1     51     b1261
2     57      d710
3     57     b1301
4     57      d550

答案 1 :(得分:4)

dplyr对此有好处,因为它有unnest

library(tidyverse)
library(stringr)
df %>%
    mutate(unpacked = str_split(abilities, ";")) %>%
    unnest %>%
    mutate(abilities = str_trim(unpacked))

答案 2 :(得分:1)

另一个选项是cSplit

 library(splitstackshape)
 cSplit(df1, 'abilities', '; ', 'long')
 #   number abilities
 #1:     51     b1261
 #2:     57      d710
 #3:     57     b1301
 #4:     57      d550