First, let's generate a dataset.
response<-c((rnorm(20, mean = 2.3, sd = 1)),rnorm(20, mean = 4.7, sd = 2.3))
#Generating some random normal distributions using rnorm.
#That first number is the length (i.e., how many numbers you want in each set).
#So, here's how I have my data to begin with:
#Use str(original.data) to check if the response variable is numeric and the others are factors.
#And here's what I want it to look like:
#Start the reshape2 package.
melt.data<-melt(original.data,id=c("levels", "groups", "individual"),
measured=c("response")) #variable measured is response
melt.data #show data
# levels groups individual variable value #1 A group1 1 response 0.8034790 #2 A group2 1 response 2.7244518 #3 A group3 1 response 2.0623880#Etc. on to 40 rows.
#Set the variable here. "groups" is the factor that we want to make #up our four new columns.
#Here is what melt.data looks like now:
# levels groups individual variable value #1 A group1 1 group1 0.8034790 #2 A group2 1 group2 2.7244518 #3 A group3 1 group3 2.0623880
#Etc. on to 40 rows.
#List the factors that do NOT go as the new columns.
#Because we want groups to be the new columns, you list only individual and levels.
#Then after ~ put "variable"and that you want the means of this measurement for each combination of individual and levels.
#In this example, you just have one observation for each group in each individual in each level,
#so it should be the same as your original data.
#If you took more than one observation for each individual in each level and each group,
#and didn't include it in the list with individual and levels,
#using mean would allow you to average across those.
#This might happen if you took multiple observations and hadn't averaged them yet,
#or had an additional factor that you are not examining in this analysis.
#Use dcast if you want a data frame as the resulting object;
#use acast if you want a matrix or vector.
#("cast" is the old function from the original reshape package;
#with the old function you had to specify data.frame if you wanted a data frame).
#shows your dataset, now with measurements for each individual in a row,
#with one column each for group1, group2, group3, and group4
#instead of classified by factors in the old "groups" column.
#It's just like we wanted at the beginning!
#Did you start with data in the column form?
#Or do you want to put your data back the way it was
#but now as means for each combination of factors?
#For example, one use I've found for this is to
#put my data in the multi-column form, use na.omit
#to get rid of any individuals with missing data,
#and then convert back to long form.
data.longform #view the dataset back in a long one-column form.