Pardon my new-ness to the R world, thank you kindly in advance for your help.
I would like to analyze the data from an experiment.
The data comes in in Long
There’s a package called tidyr that makes melting and reshaping data frames much easier. In your case, you can use tidyr::spread
straightforwardly:
result = spread(df, Item, Resp)
This will however fill missing entries with NA
:
User_id location age gender A B C D E G H
1 1 CA 22 M 1 -1 -1 1 -1 NA NA
2 2 MD 27 F -1 1 1 NA 1 -1 -1
You can fix this by replacing them:
result[is.na(result)] = 0
result
# User_id location age gender A B C D E G H
# 1 1 CA 22 M 1 -1 -1 1 -1 0 0
# 2 2 MD 27 F -1 1 1 0 1 -1 -1
… or by using the fill
argument:
result = spread(df, Item, Resp, fill = 0)
For completeness’ sake, the other way round (i.e. reproducing the original data.frame
) works via gather
(this is usually known as “melting”):
gather(result, Item, Resp, A : H)
— The last argument here tells gather
which columns to gather (and it supports the concise range syntax).