根据在R中的一列分割的字符串重新构建数据帧 [英] reshape dataframe based on a string split in one column in R

查看:129
本文介绍了根据在R中的一列分割的字符串重新构建数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据结构

ID  Type  Values
1   A     5; 7; 8
2   A     6
3   B     2; 3

,我想使用R将其重新整理为以下内容:

and I would like to reshape it to the following using R:

ID  Type  Values
1   A     5
1   A     7
1   A     8
2   A     6
3   B     2
3   B     3

我一直在试图找出如何与plyr做,但没有任何成功。这样做最好的方法是什么?

I've been trying to work out how to do it with plyr but without any success. What is the best way to do this?

推荐答案

既然你要求一个 plyr 解决方案,这里你去:

Since you asked for a plyr solution, here you go:

ddply(df, .(Type), function(foo) {
    values <- unlist(strsplit(c(foo$Values), ";"))
    data.frame(Type = rep(unique(foo$Type), length(values)), Values = values)
    })

这篇关于根据在R中的一列分割的字符串重新构建数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆