Nicholas Hayden
Nicholas Hayden

Reputation: 523

R Data Restructuring - Melt2

 V1      V2      V3      V4
 Control Control Unknown Unknown
 0       2       0       2
 66      10      90      70

The rows mean: Experiment, Time, Length, respectively

How would you restructure the above data to look so it looks like the below using melt2?

V1      V2 V3
Control 0  66
Control 2  10
Unknown 0  90
Unknown 2  70

Thanks for your time.

p.s: I am novice programmer trying to learn R

Upvotes: 0

Views: 129

Answers (1)

Parfait
Parfait

Reputation: 107767

You can use base R (meaning no external library/package) and simply use transpose.

df <- data.frame(V1=c("Control", "0", "66"),  
                 V2=c("Control", "2", "10"),  
                 V3=c("Unknown", "0", "90"),
                 V4=c("Unknown", "2", "70"))    

reshape_df <- as.data.frame(t(df))
row.names(reshape_df) <- NULL

# CLEAN-UP
names(reshape_df)[1] <- "Experiment"
reshape_df$Experiment <- as.character(reshape_df$Experiment)
names(reshape_df)[2] <- "Time"
reshape_df$Time <- as.numeric(as.character(reshape_df$Time))
names(reshape_df)[3] <- "Length"
reshape_df$Length <- as.numeric(as.character(reshape_df$Length))

Output

Experiment  Time   Length
Control     0      66
Control     2      10
Unknown     0      90
Unknwon     2      70

Upvotes: 1

Related Questions