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

Hea*_*oes 0 split r

我有一组数据:

 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)
Run Code Online (Sandbox Code Playgroud)

它看起来像这样:

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

在 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
Run Code Online (Sandbox Code Playgroud)

我不确定我是否可以在 R 中做到这一点?有人可以帮忙吗?
R 非常新,所以一些解释将不胜感激。

tal*_*lat 5

这是一个基本的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)
Run Code Online (Sandbox Code Playgroud)

生成的 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
Run Code Online (Sandbox Code Playgroud)