简体   繁体   English

R:转换数据(因子值作为列名)

[英]R: transform data (factor value as column name)

I have a dataset that I want to transform in to another format: 我有一个数据集,我想转换为另一种格式:

The data looks like this (for privacy issue, I cannot put the original data): 数据看起来像这样(对于隐私问题,我不能把原始数据):

ID1 ID2 Month   Value
1   A   Jan-03  10
2   B   Jan-03  11
1   A   Feb-03  12
2   B   Feb-03  13
1   A   Mar-03  14
2   B   Mar-03  15

I want the Month column to be as the column name, and the format looks like this: 我希望Month列作为列名,格式如下所示:

ID1 ID2 Jan-03  Feb-03  Mar-03
1   A   10  12  14
2   B   11  13  16

Thanks! 谢谢!

You could try 你可以试试

 df$Month <- factor(df$Month, levels=unique(df$Month))
 reshape(df, idvar=c('ID1', 'ID2'), timevar='Month', direction='wide')
 #  ID1 ID2 Value.Jan-03 Value.Feb-03 Value.Mar-03
 #1   1   A           10           12           14
 #2   2   B           11           13           15

Or 要么

library(reshape2)
dcast(df, ID1+ID2~Month, value.var='Value')
#   ID1 ID2 Jan-03 Feb-03 Mar-03
#1   1   A     10     12     14
#2   2   B     11     13     15

Or 要么

library(tidyr)
spread(df, Month, Value)
#   ID1 ID2 Jan-03 Feb-03 Mar-03
#1   1   A     10     12     14
#2   2   B     11     13     15

data 数据

df <- structure(list(ID1 = c(1L, 2L, 1L, 2L, 1L, 2L), ID2 = c("A", 
"B", "A", "B", "A", "B"), Month = c("Jan-03", "Jan-03", "Feb-03", 
"Feb-03", "Mar-03", "Mar-03"), Value = 10:15), .Names = c("ID1", 
"ID2", "Month", "Value"), class = "data.frame", row.names = c(NA, 
-6L))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM