将一列中的字符串转换为多列

时间:2017-03-24 17:50:32

标签: r dataframe dataset plyr

我的数据集如下所示:

"Fruit","Allocation"

apple,Anna:1|Bob:2|Chloe:3

banana,Anna:3|Bob:2|Chloe:1

我想将它转换为下面的代码:

"Fruit","Anna","Bob","Chloe"

apple,1,2,3

banana,3,2,1

将数据集转换为 R 中所需输出的最简单方法是什么?

1 个答案:

答案 0 :(得分:1)

我们可以使用tidyverse执行此操作。通过将separate_rows处的“分配”列拆分,然后将|“分配”列拆分为两列“名称”,“数字”,使用separate将“广泛”转换为“长” 'sep=":"spread从'long'到'wide'

library(tidyverse)
separate_rows(df1, Allocation, sep="[|]") %>%
        separate(Allocation, into = c("Name", "Number")) %>%
        spread(Name, Number)
#   Fruit Anna Bob Chloe
#1  apple    1   2     3
#2 banana    3   2     1

数据

df1 <- structure(list(Fruit = c("apple", "banana"), Allocation = c("Anna:1|Bob:2|Chloe:3", 
"Anna:3|Bob:2|Chloe:1")), .Names = c("Fruit", "Allocation"),
 class = "data.frame", row.names = c(NA, -2L))