[R] Transform dataframe
Jeff Newmiller
jdnewmil at dcn.davis.ca.us
Sun Apr 22 19:27:25 CEST 2012
On Sun, 22 Apr 2012, David Studer wrote:
> Hi everyone!
>
> I have to following question: I have three items that had
> to be ordered (e.g. three persons were rating var1 on the
> first rank):
>
> var1 var2 var3
> 1 2 3
> 2 1 3
> 1 3 2
> 1 2 3
>
> Now I'd like to have the data.frame "the other way round", so that
> the ranks are in the columns:
>
> rank1 rank2 rank3
> var1 var2 var3
> var2 var1 var3
> var1 var3 var2
> var1 var2 var3
>
> Can anyone help me achieving this?
>
> # code:
>
> var1<-c(1,2,1,1)
> var2<-c(2,1,3,2)
> var3<-c(3,3,2,3)
> df<-as.data.frame(cbind(var1,var2,var3,var4))
>
> ??
>
> Thank you very much!
> David
>
> [[alternative HTML version deleted]]
Please fix your email settings to send text to this list...
tc <- textConnection(
"var1 var2 var3
1 2 3
2 1 3
1 3 2
1 2 3
")
dta <- read.table( tc, as.is=TRUE, header=TRUE )
close( tc )
dta$respondent <- letters[1:4]
library(reshape2)
dtalong <- melt( dta, id="respondent" )
# levels specified to guard against sorting problems if more
# than 9 rankings
dtalong$rank <- factor( paste( "rank", dtalong$value, sep="" )
, levels=paste( "rank"
, sort( unique( dtalong$value ) )
, sep="" )
, ordered=TRUE )
dta2 <- dcast( dtalong, respondent ~ rank, value.var="variable" )
---------------------------------------------------------------------------
Jeff Newmiller The ..... ..... Go Live...
DCN:<jdnewmil at dcn.davis.ca.us> Basics: ##.#. ##.#. Live Go...
Live: OO#.. Dead: OO#.. Playing
Research Engineer (Solar/Batteries O.O#. #.O#. with
/Software/Embedded Controllers) .OO#. .OO#. rocks...1k
More information about the R-help
mailing list