[R] Persons with objects –> Objects and persons
Marek Lutonský
marek at lutonsky.net
Sun Mar 15 12:46:40 CET 2015
Hi Jim,
thank you very much for the code.
Marek
On Sun, Mar 15, 2015 at 11:46 AM, Jim Lemon <drjimlemon at gmail.com> wrote:
> Hi mareki,
> The transformation is not too difficult, but the table format in your
> example will cause a bit of difficulty. The following function from the
> plotrix package:
>
> categoryReshape<-function(x) {
> dimx<-dim(x)
> if(is.null(dimx) || dimx[2]==1)
> stop("Can only reshape a matrix or data frame with at least two columns")
> row_values<-sort(unique(x[,1]))
> column_values<-sort(unique(x[,2]))
> newx<-
>
> as.data.frame(matrix(0,nrow=length(row_values),ncol=length(column_values)))
> for(row in 1:dimx[1]) {
> row_index<-which(row_values %in% x[row,1])
> column_index<-which(column_values %in% x[row,2])
> newx[row_index,column_index]<-1
> }
> names(newx)<-column_values
> rownames(newx)<-row_values
> return(newx)
> }
>
> will take a matrix or data frame like this:
>
> table1<-read.table(text="object,person
> A,1
> A,2
> A,3
> A,4
> A,5
> B,1
> B,2
> B,3
> C,2
> C,3
> C,5
> D,4
> E,2
> E,3
> E,4
> E,5",sep=",",header=TRUE)
>
> and transform it into a data frame like this:
>
> categoryReshape(table1)
> 1 2 3 4 5
> A 1 1 1 1 1
> B 1 1 1 0 0
> C 0 1 1 0 1
> D 0 0 0 1 0
> E 0 1 1 1 1
>
> Then if you take each column and format it like this;
>
> concat_labels<-function(x,labels)
> return(paste(labels[as.logical(x)],collapse=";"))
> sapply(table2,concat.labels,rownames(tables))
>
> 1 2 3 4 5
> "A;B" "A;B;C;E" "A;B;C;E" "A;D;E" "A;C;E"
>
> you have pretty much what you want.
>
> Jim
>
>
> On Sun, Mar 15, 2015 at 9:02 AM, marekl <marek.r at lutonsky.net> wrote:
>
>> Hi,
>>
>> I have a table with persons in rows and objects associated to these
>> persons.
>> And I need to transform it to table with objects in rows and persons next
>> to
>> them. As it is shown on the picture.
>>
>> <http://r.789695.n4.nabble.com/file/n4704655/Persons%2C_Objects.png>
>>
>> Can you please help me how to make this transformation in R?
>>
>> Thank you
>>
>>
>>
>> --
>> View this message in context:
>> http://r.789695.n4.nabble.com/Persons-with-objects-Objects-and-persons-tp4704655.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list