Below is an example of a function in R that analyzes a dataset with 5 columns: caseid, control1, control2, control3, and value.
r
# Load necessary libraries
library(dplyr)
library(ggplot2)
# Define the function
analyze_data <- function(data) {
# Check if the input data is a data frame
if (!is.data.frame(data)) {
stop("Input data must be a data frame")
}
# Check if the required columns exist
required_columns <- c("caseid", "control1", "control2", "control3", "value")
if (!all(required_columns %in% colnames(data))) {
stop("Data must contain the following columns: caseid, control1, control2, control3, value")
}
# Summary statistics
summary_stats <- data %>%
summarise(
mean_value = mean(value, na.rm = TRUE),
sd_value = sd(value, na.rm = TRUE),
min_value = min(value, na.rm = TRUE),
max_value = max(value, na.rm = TRUE)
)
# Correlation analysis
correlation_matrix <- cor(data[, c("control1", "control2", "control3", "value")], use = "pairwise.complete.obs")
# Linear regression analysis
model <- lm(value ~ control1 + control2 + control3, data = data)
model_summary <- summary(model)
# Return the results
list(
summary_stats = summary_stats,
correlation_matrix = correlation_matrix,
model_summary = model_summary
)
}
# Example usage
# Create a sample dataset
set.seed(123)
data <- data.frame(
caseid = 1:100,
control1 = rnorm(100),
control2 = rnorm(100),
control3 = rnorm(100),
value = rnorm(100)
)
# Analyze the data
results <- analyze_data(data)
# Print the results
print(results$summary_stats)
print(results$correlation_matrix)
print(results$model_summary)
# Visualize the data
ggplot(data, aes(x = control1, y = value)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
ggplot(data, aes(x = control2, y = value)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
ggplot(data, aes(x = control3, y = value)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
Function Explanation
The analyze_data function takes a data frame as input and performs the following analyses:
Summary Statistics: Calculates the mean, standard deviation, minimum, and maximum of the value column.
Correlation Analysis: Computes the correlation matrix for the control1, control2, control3, and value columns.
Linear Regression Analysis: Fits a linear regression model to predict value based on control1, control2, and control3.
The function returns a list containing the summary statistics, correlation matrix, and linear regression model summary.
Example Usage
The example usage demonstrates how to create a sample dataset, analyze it using the analyze_data function, and visualize the relationships between the controls and the value column using ggplot2.