如何根据R中第二列的值将数据帧的列拆分为两个不同的列?

时间:2018-04-16 18:38:22

标签: r dataframe

我有一个包含三列的数据框:一个包含ID,一个包含颜色ID,另一个包含颜色。每个Id与两种颜色ID和颜色相关联。我想要做的是将颜色列分成两个不同的列,color.1和color.2,color.1包含与颜色ID“a”和color.2相关联的所有颜色.2包含与a关联的所有颜色颜色ID“b”。以下代码举例说明了我的输入和所需输出:

# Building input dataframe.
df.input <- data.frame(id = c(1, 1, 2, 2, 3, 3),
                       color.id = c("a", "b", "a", "b", "a", "b"),
                       color = c("red", "orange", "green", "blue", "yellow", "purple"))

# Visualizing input dataframe.
df.input

# Building desired output dataframe.
df.output <- data.frame(id = c(1, 2, 3),
                        color.1 = c("red", "green", "yellow"),
                        color.2 = c("orange", "blue", "purple"))

# Visualizing desired output dataframe.
df.output

1 个答案:

答案 0 :(得分:1)

使用spread

library(tidyr)
df.input %>% spread(color.id, color)

  id      a      b
1  1    red orange
2  2  green   blue
3  3 yellow purple