简体   繁体   中英

Using dplyr or tidyr to reshape dataframe based on values in three columns

I need to reshape my dataframe based on values on columns 'group', 'model' and 'qsec'. Using the mtcars data as an example, would be possible to use dplyr or tidyr to achieve this?

I need to reshape a very large dataframe, and unfortunately i don't know how to use dplyr to resolve this problem.

df<-mtcars[1:3,]
df$model <- rownames(df)
row.names(df)<-NULL

df<-df[rep(seq_len(nrow(df)), each=2),]

df$group <- c("A","B","A","C","A","B")


####
> df

     mpg cyl disp  hp drat    wt  qsec vs am gear carb         model group
1   21.0   6  160 110 3.90 2.620 16.46  0  1    4    4     Mazda RX4     A
1.1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4     Mazda RX4     B
2   21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 Mazda RX4 Wag     A
2.1 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 Mazda RX4 Wag     C
3   22.8   4  108  93 3.85 2.320 18.61  1  1    4    1    Datsun 710     A
3.1 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1    Datsun 710     B

#

I need to reshape in a way that each column would be a group (A,B or C) and as the row.names, each one of the car model belonging to each group. The values would be the ones on 'qsec' columns, with zeros for cases that a group don't have any 'qsec' value.

df_result <- data.frame(A = c(16.46,17.02,18.61), B = c(16.46,0,18.61), C = c(0,17.02,0)) 
row.names(df_result) <- unique(df$model)

> df_result
                  A     B     C
Mazda RX4     16.46 16.46  0.00
Mazda RX4 Wag 17.02  0.00 17.02
Datsun 710    18.61 18.61  0.00

I think this is what you want:

library(tidyverse)

df2 <- df%>%
select(group, model, qsec)%>%
  spread(key = group, value = qsec)

row.names(df2) <- df2$model

df_final <- df2[-1]

Using dcast from reshape2 and replace_na from tidyr :

df <- df %>%
  select(model, qsec, group) %>%
  dcast(model ~ group, value.var = "qsec") %>%
  replace_na(list(A = 0, B = 0, C = 0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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