##Script for reading processed versions ofbird landmarks used in analyses of Navalon et al. (2022) "Environmental structure in the evolutionary radiation of bird skeletons". Written by Roger Benson 06 September 2022

require( geomorph )

	setwd( "~/Desktop/Recent items/R functions Roger Benson/Bird landmark datasets Navalon November 2021 submission/Bird_processed_landmarks_Navalon_2022" )	##Set as working directory the "Bird_processed_landmarks_Navalon_2022" folder
	
	##Read all the names of different data series, including allometry-free and proportions-free versions of landmarks
		folder.names <- list.files( )[ !grepl( ".csv" , list.files( ) ) ]

	##Loop over the folder names, reading each data series and compiling to arrays that can be easily analysed using functions from e.g. geomorph. Note that no Procrustes superposition is needed because this was already done during data processing.
		for( read.landmarks in 1:length( folder.names) ){
	
			folder.name <- folder.names[ read.landmarks ]
				csv.list <- list.files( folder.name , full.names = T )
					taxon.names <- list.files( folder.name , full.names = F )
						taxon.names <- gsub( paste( "_" , folder.name , ".csv" , sep = "" ) , "" , taxon.names )
				
			landmark.list <- lapply( csv.list , read.csv )
				rownames.temp <- landmark.list[[ 1 ]][,1]
				landmark.list <- lapply( landmark.list , function(X){X[,2:4]})
				
			output.landmarks.array <- array( unlist( landmark.list ) , dim = c( nrow( landmark.list[[1]] ) , ncol( landmark.list[[1]] ) , length( landmark.list ) ) )
				dimnames( output.landmarks.array )[[ 1 ]] <- rownames.temp
				dimnames( output.landmarks.array )[[ 2 ]] <- c( "x" , "y" , "z" )
				dimnames( output.landmarks.array )[[ 3 ]] <- taxon.names
					
			assign( folder.name , output.landmarks.array )
		}
	
	##View some example data 
		element <- "skull"	##Set element, 13 options: "skull", "mandible", "scapula", "coracoid", "sternum", "humerus", "radius", "ulna", "carpometacarpus", "synsacrum", "femur", "tibiotarsus" , "tarsometatarsus"
		data.type <- "proportions.free"	##Set data type. Two options: "allometry.free" and "proportions.free"
			data.temp <- get( paste( element, data.type , sep = "." ) )
			
		if( element != "beak" ){ colours <- read.csv( paste( "Colours_" , element , "_min.csv" , sep = "" ) ) 
									colours <- c( colours[,2] )	}	
			
		specimen <- "Ramphastos_ambiguus"	##Set a specimen to view. There are 228 specimens in total. Specimens can be selected using either names - see dimnames(data.temp)[[3]] -, or numbers
		
		if( element != "beak" ){ plot3d( data.temp [,,specimen] , col = colours , size = 10 , asp = "iso" ) }
		if( element == "beak" ){ plot3d( data.temp [,,specimen] , size = 10 , asp = "iso" ) }		