基于 strsplit 将 Data.Frame 重组为多行

标签 r strsplit

我有这样的数据结构。

    structure(list(id = c("4031", "1040;2040;3040", "4040", 
    "1050;2050;3050"), description = c("Sentence A", 
    "Sentence B", "Sentence C", 
    "Sentence D")), row.names = 1:4, class = "data.frame")

              id description
1           4031  Sentence A
2 1040;2040;3040  Sentence B
3           4040  Sentence C
4 1050;2050;3050  Sentence D

我想重组数据,以便 ids 带有“;”分成单独的行 - 我想要这样:

structure(list(id = c("4031", "1040","2040","3040", "4040", 
"1050","2050","3050"), description = c("Sentence A", 
"Sentence B","Sentence B","Sentence B", "Sentence C", 
"Sentence D","Sentence D","Sentence D")), row.names = 1:8, class = "data.frame")

   id description
1 4031  Sentence A
2 1040  Sentence B
3 2040  Sentence B
4 3040  Sentence B
5 4040  Sentence C
6 1050  Sentence D
7 2050  Sentence D
8 3050  Sentence D

我知道我可以用 strsplit 分割 id 列但无法找到一种有效的方法将其转换为没有循环的行

strsplit( as.character( a$id ) , ";" )

最佳答案

使用 R 基础:

> IDs <- strsplit(df$id, ";")
> data.frame(ID=unlist(IDs), Description=rep(df$description, lengths(IDs)))
    ID Description
1 4031  Sentence A
2 1040  Sentence B
3 2040  Sentence B
4 3040  Sentence B
5 4040  Sentence C
6 1050  Sentence D
7 2050  Sentence D
8 3050  Sentence D

关于基于 strsplit 将 Data.Frame 重组为多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56484560/

相关文章:

r - R,生成数字向量仅包含0和1,且具有一定的长度

r - 在data.frame中按行拆分并按列分配结果

regex - 为什么 strsplit 返回一个列表

regex - R在data.frame中获取双/三重姓氏的首字母

r - 使用 strsplit 分割字符串并为分割的一部分创建一个新向量

r - 在 R 中拆分不分隔的字符串和数值变量

r - 如何创建 R 的精简版本?

r - 带 ggplot 的多面饼图

r - pryr::mem_used() 在内存单位(MB、GB、...)之间的转换

r - 如何自定义或显示模式栏?