如何strsplit数据框列并相应地复制行? [复制]

2024-01-12

我有一个像这样的数据框:

> df <- data.frame(Column1=c("id1", "id2", "id3"), Column2=c("text1,text2,text3", "text4", "text5,text6"), Column3=c("text7", "text8,text9,text10,text11", "text12,text13"))

> df
  Column1           Column2                   Column3
1     id1 text1,text2,text3                     text7
2     id2             text4 text8,text9,text10,text11
3     id3       text5,text6             text12,text13

如何将其转换为这种格式?

  Column1 variable                     value
1     id1  Column2                     text1
2     id1  Column2                     text2
3     id1  Column2                     text3
4     id2  Column2                     text4
5     id3  Column2                     text5
6     id3  Column2                     text6
7     id1  Column3                     text7
8     id2  Column3                     text8
9     id2  Column3                     text9
10    id2  Column3                    text10
11    id2  Column3                    text11
12    id3  Column3                    text12
13    id3  Column3                    text13

我想第一步是melt()数据框(顺便说一句,我应该担心这个警告吗?):

> library(reshape2)    
> mdf <- melt(df, id.vars="Column1", measure.vars=c("Column2", "Column3"))
> mdf
  Column1 variable                     value
1     id1  Column2         text1,text2,text3
2     id2  Column2                     text4
3     id3  Column2               text5,text6
4     id1  Column3                     text7
5     id2  Column3 text8,text9,text10,text11
6     id3  Column3             text12,text13
Warning message:
attributes are not identical across measure variables; they will be dropped

然后我基本上需要“strsplit()”“值”列并相应地复制行,但我想不出一种方法来做到这一点。

> strsplit(mdf$value, ",")
[[1]]
[1] "text1" "text2" "text3"

[[2]]
[1] "text4"

[[3]]
[1] "text5" "text6"

[[4]]
[1] "text7"

[[5]]
[1] "text8"  "text9"  "text10" "text11"

[[6]]
[1] "text12" "text13"

任何帮助表示赞赏!谢谢。


A data.table解决方案:

library(data.table)
mdt <- melt(setDT(df), id.vars="Column1")[,strsplit(as.character(value),",",fixed=TRUE),
                                          by=list(Column1,variable)]

结果:

> mdt
    Column1 variable     V1
 1:     id1  Column2  text1
 2:     id1  Column2  text2
 3:     id1  Column2  text3
....

您还可以使用tstrsplit函数从最新版本的data.table https://github.com/Rdatatable/data.table/wiki/Installation(v1.9.5+) 保留名称value列而不是将其重命名为V1:

mdt <- melt(setDT(df), id.vars="Column1")[,lapply(.SD, function(x) tstrsplit(x, ",", fixed=TRUE)),
                                          by=list(Column1,variable)]

结果:

> mdt
    Column1 variable  value
 1:     id1  Column2  text1
 2:     id1  Column2  text2
 3:     id1  Column2  text3
....

替代解决方案dplyr & tidyr:

library(dplyr)
library(tidyr)
mdf <- df %>% gather(variable, value, -Column1) %>% 
  transform(value = strsplit(as.character(value),",")) %>%
  unnest(value)

结果:

> mdf
   Column1 variable  value
1      id1  Column2  text1
2      id1  Column2  text2
3      id1  Column2  text3
....

与最新版本tidyr,您还可以使用separate_rows-功能:

mdf <- df %>% 
  gather(variable, value, -Column1) %>% 
  separate_rows(value)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何strsplit数据框列并相应地复制行? [复制] 的相关文章

  • 使用 lpSolve 优化 R 团队名单

    我是 R 新手 有一个想要解决的特定幻想运动队优化问题 我见过其他帖子使用 lpSolve 来解决类似的问题 但我似乎无法理解代码 下面的示例数据表 每个球员都在一个球队中 扮演着特定的角色 有薪水 并且每场比赛都有平均得分 我需要的限制是
  • 通过 :: 调用包中的函数是一个好习惯吗

    我正在编写一些 R 函数 这些函数在其他包中使用一些有用的函数 例如stringr and base64enc 不打电话好不好library or require 首先加载这些包但要使用 直接引用我需要的功能 比如stringr str m
  • JavaScript 用空格分割字符串

    我想分割一个字符串 但我想保留空白 例如 var str my car is red var stringArray stringArray 0 my stringArray 1 stringArray 2 car stringArray
  • 在R闪亮中,如何在UI端使用在SERVER端计算的值?

    在我的 R闪亮应用程序中 我想调整我的高度d3heatmap 见包装d3热图 https cran r project org web packages d3heatmap index html 作为我的数据框行数的函数 有一个论点heig
  • R tm 包创建 N 个最常见术语的矩阵

    我有一个termDocumentMatrix使用创建的tmR 中的包 我正在尝试创建一个包含 50 个最常出现的术语的矩阵 数据框 当我尝试转换为矩阵时 出现此错误 gt ap m lt as matrix mydata dtm Error
  • R Shiny UI 子选项复选框?

    我有一个基本的 RShiny 应用程序 它有一个反应式复选框 它根据复选框中选择的数据 df 列 绘制时间序列数据 我当前的代码生成一个带有复选框输入的 UI 如下所示 Load R packages library shiny libra
  • 如何在R中的2行之间交换多个值

    我有一个大小为 10x100 的矩阵 如何交换前 30 列中第 1 行和第 2 行之间的值 我们可以反转前两行的行索引以及通过采取序列创建的列索引rounded 30 总列数用于交换行中的值 colS lt seq round ncol m
  • 获取所有参数作为列表

    R 是否提供对象 函数 方法 关键字来获取所有函数参数 使用一个例子 function a b default 会提供a and b也 在函数环境内 有没有类似的说法list 这还包括a and b在结果中 或者换一种方式 简写list a
  • 使用 sapply 的列表和矩阵

    我有一个也许是基本的问题 我在网上搜索过 我在读取文件时遇到问题 尽管如此 我还是按照 Konrad的建议设法读取了我的文件 我很欣赏这一点 How to get R to read in files from multiple subdi
  • 根据条件计算平均值

    下面是我的数据框 Row ID A B 1 0 0 2 0 0 3 0 0 4 0 1 5 0 1 6 0 1 7 62 75 0 8 100 0 9 100 0 10 100 1 11 100 1 12 100 1 13 100 1 14
  • 使用 ape 包在 R 中进行标签和色叶树状图(系统发育)

    继上一篇文章之后 r 中的标签和彩色叶树状图 https stackoverflow com questions 18802519 label and color leaf dendrogram in r 我有一个后续问题 我的问题与提到的
  • 在 R 中索引数据帧

    再会 我不明白这里的主题 就像它有效但我不明白为什么 我有这个数据库 planets df is pre loaded in your workspace Use order to create positions positions lt
  • 如何导入 .tsv 文件

    我需要读取一个表 tsvR 中的文件 test lt read table file drug info tsv Error in scan file what nmax sep dec quote skip nlines na strin
  • 使用 ggplot 未完全填充等值线图

    我正在尝试使用以下方法绘制我的第一个填充等高线图ggplot 根据我的数据 我期待类似的结果 但我的结果是 a lt c 1 1 1 1 1 3 1 2 2 2 2 2 2 5 2 1 3 3 3 3 1 3 2 b lt c rep c
  • 检索除指定一列之外的所有 DataFrame [重复]

    这个问题在这里已经有答案了 有没有办法选择 pandas DataFrame 对象中除一列之外的所有列 我已经看到了删除列的方法 但我不想这样做 use drop method df drop column name axis 1
  • 从频率表生成 data.frame

    我在 2 4 数组中有包含 500 个观察值的合成数据 datax array c 120 181 50 43 41 33 24 8 dim c 2 4 dimnames datax list gender c male female pu
  • 如何在 rmarkdown 中显示带有 results='asis' 的格式化 R 输出

    当使用 results asis 时 有没有办法在 rmarkdown knitr 中显示格式化程序 R 输出 一个例子是以下函数 myfun lt function cat hello n cat c one 1 two 2 然后 该块将
  • 替换向量中非 %in% 向量的值

    简短的问题 我可以像这样替换某些变量值 values lt c a b a b c a b df lt data frame values 将 df values 的所有值替换为 x 其中值是neither a 或 b 输出应该是 c a
  • R data.table fread 使用不带标题的命名 colClasses(例如没有 col.names?)

    更新 2016 年 6 月 col names 已添加到 data table 1 9 6 所以问题已经结束 每个人都非常高兴 我想我现在可以将所有 read csv 调用转换为 fread 调用 而不必担心破坏 原问题 使用数据表1 9
  • Pandas:数据帧累积和,如果其他列为假则重置[重复]

    这个问题在这里已经有答案了 我有一个包含 2 列的数据框 这里的目标很简单 如果行列设置为 False 则重置 df cumsum df value condition 0 1 1 1 2 1 2 3 1 3 4 0 4 5 1 想要的结果

随机推荐