我的数据集如下所示:
"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 中所需输出的最简单方法是什么?
答案 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))