alaa goupi alaa goupi -4 years ago 71
R Question

Reshaping data in R from CSV file

I have data from a CSV file in the following format:

Timestamp variable value
03/10/2014 var1 10
04/10/2014 var1 11
01/10/2014 var2 5
02/10/2014 var2 16
03/10/2014 var2 17
04/10/2014 var2 18


And I want to get the data in the following format:

Timestamp var1 var2
01/10/2014 NaN 5
02/10/2014 NaN 16
03/10/2014 10 17
04/10/2014 11 18


I want to reshape this data in R. Any suggestion please.

Answer Source

In R you can use dcast

library(reshape2)
df <- rbind.data.frame(c("01/10/2014", "var1", 10),
        c("02/10/2014", "var1", 11),
        c("01/10/2014", "var2", 5),
        c("02/10/2014", "var2", 16))
colnames(df) <- c("Timestamp", "variable", "value")
dcast(df, Timestamp~variable)
#    Timestamp var1 var2
# 1 01/10/2014   10    5
# 2 02/10/2014   11   16

Since you are a beginner user, I would also recommend looking at the melt function to perform the opposite

df2 <- dcast(df, Timestamp~variable)
melt(df2, id.vars="Timestamp")
#    Timestamp variable value
# 1 01/10/2014     var1    10
# 2 02/10/2014     var1    11
# 3 01/10/2014     var2     5
# 4 02/10/2014     var2    16
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download