如何将数据帧行转换为R中的列?

时间:2017-09-13 07:26:55

标签: r dataframe transform reshape melt

我有一个需要转换的数据框。我需要根据列的值将行更改为唯一列。

前:

输入数据框

| column_1 | column_2 |
-----------------------
|   A      |     B    |
|   A      |     C    |
|   B      |     E    |
|   B      |     C    |
|   C      |     F    |
|   C      |     G    |

输出数据框

| column_1 | column_2 | column_3 |
----------------------------------
|   A      |     B    |     C    |
|   B      |     E    |     C    |
|   C      |     F    |     G    |

最终的DataFrame应该包含column_1中的所有唯一值,而来自输入DataFrame的column_2中的值将作为新列添加到新的DataFrame中,即Column_2和Column_3。

我曾尝试在R中使用reshape和fusion软件包,但是我的数据框出错了。

3 个答案:

答案 0 :(得分:2)

我们可以使用dplyr中的cSplitsplitstackshape功能。它也适用于每组有两个以上值的情况。

library(dplyr)
library(splitstackshape)
dt2 <- dt %>%
  group_by(column_1) %>%
  summarise(column_2 = toString(column_2)) %>%
  cSplit("column_2") %>%
  setNames(paste0("column_", 1:ncol(.)))

dt2
   column_1 column_2 column_3
1:        A        B        C
2:        B        E        C
3:        C        F        G

数据

dt <- data.frame(column_1 = c("A", "A", "B", "B", "C", "C"),
                 column_2 = c("B", "C", "E", "C", "F", "G"),
                 stringsAsFactors = FALSE)

答案 1 :(得分:1)

假设column_1中的每个值总是有2行。

为第一个data.table中的每个column_1元素提取第一行,然后在第二个data.table中提取最后一行,最后将它们合并为一个新的data.table

library(data.table)

df <- data.frame(column_1=c("A","A","B","B","C","C"),column_2=c("B","C","E","C","F","G"))
df <- as.data.table(df)
setkey(df,column_1)
first_part <- df[J(unique(column_1)), mult = "first"]
second_part <- df[J(unique(column_1)), mult = "last"]
setnames(second_part,"column_2","column_3")

new_df <- merge(first_part,second_part, by="column_1")

   column_1 column_2 column_3
1:        A        B        C
2:        B        E        C
3:        C        F        G

答案 2 :(得分:0)

以下是dplyrtidyr的简短解决方案:

library(dplyr)
library(tidyr)
df %>% mutate(col = c("column_2","column_3")[duplicated(column_1)+1]) %>%
  spread(col,column_2)

#   column_1 column_2 column_3
# 1        A        B        C
# 2        B        E        C
# 3        C        F        G

一般解决方案:

df <- data.frame(column_1 = c("A", "A", "B", "B", "C", "C","A","B","C"),
                 column_2 = c("B", "C", "E", "C", "F", "G","X","Y","Z"),
                 stringsAsFactors = FALSE)

df %>% group_by(column_1) %>%
  mutate(col=paste0("column_",row_number()+1)) %>%
  spread(col,column_2) %>% ungroup

# # A tibble: 3 x 4
#   column_1 column_2 column_3 column_4
# *    <chr>    <chr>    <chr>    <chr>
# 1        A        B        C        X
# 2        B        E        C        Y
# 3        C        F        G        Z