如何将数据帧行转换为 R 中的列? [英] How to transform a dataframes row into columns in R?
问题描述
我有一个需要转换的数据框.我需要根据列的值将行更改为唯一的列.
I have a data frame which I need to transform. I need to change the rows into unique columns based on the value of a column.
例如:
输入数据帧
| 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.
The final DataFrame should have all the unique values in column_1 and the values from column_2 from input DataFrame will be added as new columns in new DataFrame i.e. Column_2 and Column_3.
我曾尝试在 R 中使用 reshape 和melt 包,但我得到了错误的数据框.
I have tried to use reshape and melt packages in R but I am getting erroneous data frame.
推荐答案
我们可以使用 splitstackshape
中的 dplyr
和 cSplit
函数.它也适用于每组有两个以上值的情况.
We can use the dplyr
and cSplit
function from the splitstackshape
. It will also work for cases when there are more than two values per group.
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)
这篇关于如何将数据帧行转换为 R 中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!