Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2014
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. # Initialize data in row format in first data fram:
  2. v1<-c("A",1,1.3)
  3. v2<-c("A",2,1.8)
  4. v3<-c("A",3,2.4)
  5. v4<-c("B",1,0.8)
  6. v5<-c("B",3,1.7)
  7. first_DF<-data.frame(matrix(c(v1,v2,v3,v4,v5),ncol=3, nrow=5,byrow=TRUE,dimnames=list(NULL,c("Individual","DayAlive","Length"))), stringsAsFactors=FALSE)
  8.  
  9. # Convert to column format in second data frame:
  10. individual_IDs<-unique(first_DF$"Individual")
  11. days_alive<-unique(first_DF$"DayAlive")
  12.  
  13. # Initialize second DF by subsetting a single row for each individual from the first DF
  14. second_DF<-data.frame(first_DF[which(first_DF$"Individual" %in% individual_IDs & first_DF$"DayAlive" %in% 1),1], stringsAsFactors=FALSE)
  15. names(second_DF)<-"Individual"
  16. initial_DF_width<-dim(second_DF)[2]
  17.  
  18. # Move 'Length' data into the columns as each 'day alive' column is created:
  19. for(i in 1:length(days_alive)){
  20. current_day<-days_alive[i]
  21. second_DF<-cbind(second_DF,matrix(ncol=1, nrow=nrow(second_DF),dimnames=list(NULL,paste("Day ",current_day," Length"))))
  22.  
  23. for(j in 1:length(individual_IDs)){
  24. current_individualID<-individual_IDs[j]
  25. length<-first_DF[which(first_DF$"Individual" %in% current_individualID & first_DF$"DayAlive" %in% current_day),"Length"]
  26. second_DF[j,i+initial_DF_width]<-length
  27. }
  28. }
  29.  
  30. library('reshape2')
  31.  
  32. dcast(first_DF, Individual ~ DayAlive)
  33. # Individual 1 2 3
  34. # 1 A 1.3 1.8 2.4
  35. # 2 B 0.8 <NA> 1.7
  36.  
  37. for(i in 1:length(days_alive)){
  38. current_day<-days_alive[i]
  39. second_DF<-cbind(second_DF,matrix(ncol=1, nrow=nrow(second_DF),dimnames=list(NULL,paste("Day ",current_day," Length"))))
  40.  
  41. for(j in 1:length(individual_IDs)){
  42. current_individualID<-individual_IDs[j]
  43.  
  44. # I changed "length" to "length2" to avoid confusion with the
  45. # function length(). You also don't need which() here.
  46. length2 <- first_DF[first_DF$Individual %in% current_individualID
  47. & first_DF$DayAlive %in% current_day, "Length"]
  48. if (length(length2) > 0) {
  49. second_DF[j, i + initial_DF_width] <- length2
  50. } else {
  51. second_DF[j, i + initial_DF_width] <- NA
  52. }
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement