使用R将一个单元格中的数据拆分为多行

时间:2017-08-24 14:59:53

标签: r split

我有一组数据:

 name<-c("A","B","C")
 type<-c("U","","D")
 content<-c("ABC (0001 - test), CCC (0002 - test1), DDD (0004 - test 2)", "CCC (0002 - test1)", "N/A")
 data<-data.frame(name,type,content)

看起来像这样:

  name type                                                    content
  A    U     ABC (0001 - test), CCC (0002 - test1), DDD (0004 - test 2)
  B                                                  CCC (0002 - test1)
  C    D                                                           N/A

在R中,我可以将其转换为:

 name   type         content              code
 A      U            ABC (0001 - test)    0001
 A      U            CCC (0002 - test1)   0002
 A      U            DDD (0004 - test 2)  0004
 B                   CCC (0002 - test1)   0002
 C      D            N/A                  N/A

我不确定我是否可以在R中执行此操作?有人可以帮忙吗? R很新,所以一些解释将不胜感激。

2 个答案:

答案 0 :(得分:4)

这是一个基础R方法:

# split the contents by comma:
x <- strsplit(as.character(data$content), ", ", fixed = T)
# add new rows with each content:
data <- cbind(data[rep(1:nrow(data), lengths(x)), 1:2], content = unlist(x))
# extract and add the code:
data$code <- sub(".*\\((\\d+)\\s.*", "\\1", data$content)

生成的data.frame如下所示:

data
#     name type             content code
# 1      A    U   ABC (0001 - test) 0001
# 1.1    A    U  CCC (0002 - test1) 0002
# 1.2    A    U DDD (0004 - test 2) 0004
# 2      B       CCC (0002 - test1) 0002
# 3      C    D                 N/A  N/A

答案 1 :(得分:2)

library(stringr)
do.call(rbind, lapply(1:NROW(data), function(i)
    setNames(data.frame(data$name[i],
                        data$type[i],
                        unlist(strsplit(as.character(data$content[i]), ", ")),
                        str_extract(unlist(strsplit(as.character(data$content[i]), ", ")),
                                    "\\d{4}")),
             c(names(data), "Code"))))
#  name type             content Code
#1    A    U   ABC (0001 - test) 0001
#2    A    U  CCC (0002 - test1) 0002
#3    A    U DDD (0004 - test 2) 0004
#4    B       CCC (0002 - test1) 0002
#5    C    D                 N/A <NA>