[R] Indexing from two variables
Ross Dunne
DUNNER6 at tcd.ie
Wed Feb 2 19:31:44 CET 2011
Hello, thank you all for your patience and time
I am essentially trying to get disorganised data into long form for linear modelling.
I have 2 dataframes "rec" and "book"
Each row in "book" needs to be pasted onto the end of several of the rows of "rec" according to two variables in the row:" MRN" and "COURSE" which match.
I have tried the following and variations thereon to no avail:
</code>
#for each line of the recovery dataframe
#insert the one line of the "book" dataset that corresponds to the MRN AND the course-of-treatment (COURSE)
#get the mrn and course from the first line of the recovery dataframe (rec)
i=1
newlist=list()
colnames(newlist)=colnames(book)
for ( i in 1:dim(rec)[1]) {
mrn=as.numeric(as.vector(rec$MRN[i]));
course=as.character(rec$COURSE[i]);
## find the corresponding row in the book dataframe
## by generating a logical vector and using
## it to access "book"
get.vector<-as.vector(((as.numeric(as.vector(book$MRN))==mrn) & (as.character(book$COURSE)==course)))
#gives you a vector of logicals (works)
newlist[i]<-book[get.vector,] ### (doesn't work)
i=i+1;
}
</code>
If anyone has any suggestions on
1)getting this to work
2) making it more elegant (or perhaps just less clumsy)
If I have been unclear in any way I beg your pardons.
I do understand I haven't combined any data above, I think if I can generate a long-format dataframe I can combine them all on my own
Ross Dunne
MB MRCPsych
ross.dunne at tcd.ie
More information about the R-help
mailing list