KEEP IN MIND that I need to think carefully about licensing issues re: this (e.g., state that it’s MIT licensed, but that the code may also show up with the UO, and grant them free reign to do what they want with it, too)


create_spss_style_correlation_matrix_from_corr_test <- function(corr.test.object){
	# This function takes the output from the Psych package's corr.test() function and formats it like an SPSS-style correlation matrix, with r, p, and n all printed together.
	# corr.test.object should be an object from the Psych package's corr.test() function.
	# The output works with View() and write.csv()
	
	# Get the column (and thus row) names from the corr.test.object. 
	# corr.test() adds an "r." to the r-value column names, "p." to the p-value column names, etc. So we'll strip away the "r." using a Regular Expression (The Regular Expression '^r.' says "Find all instances of the beginning of a line ('^') followed by 'r.'):
	column_and_row_names <- sub("^r.", "", names(as.data.frame(corr.test.object[1])))
	
	# Create a blank dataframe with the dimensions of our correlation table.
	spss_style_correlation_matrix <- as.data.frame(
		matrix(
			nrow = length(column_and_row_names), 
			ncol = length(column_and_row_names)
		),
		row.names= column_and_row_names # Set the row names of this new dataframe.
	)
	
	# Set the column names of this new dataframe.
	colnames(spss_style_correlation_matrix) <- column_and_row_names
	
	# Go through each column in the corr.test.object, and parse the corr.test output. 
	# corr.test.object[1] has r-values. 
	# corr.test.object[2] has the value of N.
	# corr.test.object[3] has t-values
	# corr.test.object[4] has p-values.
	for(column_number in 1:ncol(as.data.frame(corr.test.object[1]))) {
		
		r_values <- t(as.data.frame(corr.test.object[1])[column_number])
		p_values <- t(as.data.frame(corr.test.object[4])[column_number])
		n_value <- corr.test.object[2]
		
		# Here, we're just pasting together output like the following:
		# r: .123
		# n: 147
		# p: .001***
		# '\r\n' is cross-platform code for "newline"
		
		spss_style_correlation_matrix[column_number] <- paste(
			"r: ",
			round( # We'll round all numbers to 3 decimal places
				r_values, 3
			),
			"\r\n",
			"p: ",
			round( # We'll round all numbers to 3 decimal places
				p_values, 3
			), 
			ifelse (p_values <= 0.05, '*', ''), # Add a star ('*') if the p-value is less than .05. Otherwise, print nothing ('').
			ifelse (p_values <= 0.01, '*', ''), # Add another star ('*') if the p-value is less than .01. Otherwise, print nothing ('').
			ifelse (p_values <= 0.001, '*', ''), # Add another star ('*') if the p-value is less than .001. Otherwise, print nothing ('').
			"\r\n",
			"n: ",
			n_value,
			sep="")
	} # End of for loop
	
	return(spss_style_correlation_matrix) # At the end of the function, make spss_style_correlation_matrix the output.
	
} # End of function.

Related

Next
Previous