简体   繁体   English

长到宽格式,字符值在r中

[英]Long to wide format with character value in r

I have a long data frame as below: 我有一个长数据框,如下所示:

   Date        Time         Type
    1            1            A
    1            2            B
    1            3            C
    2            2            C
    2            3            D 
    2            5            A
    2            7            E

I want to change it to a wide format like the following: 我想将其更改为如下所示的宽格式:

   Date      Time1    Time2    Time3   Time4    Time5    Time6   Time7
     1         A        B        C
     2                  C        D                A                E

I used the following code but it only gives me 0 and 1 values instead of 'Type' values: 我使用了以下代码,但它仅提供0和1值,而不是'Type'值:

   df_index = ddply(df, .(Date), mutate, index = paste0('Time', 1:length(Date)))
   df2 = dcast(df_index, Date ~ index, value.var = 'Type')   

Could you please help me here? 你能在这里帮我吗?

You can use tidyr (part of the fantastic tidyverse you should look into) to do this fairly easily. 您可以使用tidyr(您应该研究的梦幻般的tidyverse的一部分)来轻松完成此操作。

install.packages('tidyr')
install.packages('dplyr')

library(tidyr)
library(dplyr)

all_times <- data.frame(Time = c(1:6))
df <- data.frame(Date = c(1, 1, 1, 2, 2, 2, 2), Time = c(1, 2, 3, 2, 3, 5, 7),Type = c('A', 'B', 'C', 'C', 'D', 'A', 'E'))

spread_df <- df %>% right_join(all_times) %>% spread(Time, Type, sep = '.') %>% filter(!is.na(Date))

Edited based on PoGibas's comment 根据PoGibas的评论进行编辑

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

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