# Simulate data where foreground has extra variance in first few dimensions
set.seed(123)
n_f <- 100
n_b <- 150
n_features <- 50
# Background: standard normal noise
X_b <- matrix(rnorm(n_b * n_features), nrow=n_b, ncol=n_features)
colnames(X_b) <- paste0("Feat_", 1:n_features)
# Foreground: background noise + extra variance in first 5 features
X_f_signal <- matrix(rnorm(n_f * 5, mean=0, sd=2), nrow=n_f, ncol=5)
X_f_noise <- matrix(rnorm(n_f * (n_features-5)), nrow=n_f, ncol=n_features-5)
X_f <- cbind(X_f_signal, X_f_noise) + matrix(rnorm(n_f * n_features), nrow=n_f, ncol=n_features)
colnames(X_f) <- paste0("Feat_", 1:n_features)
rownames(X_f) <- paste0("SampleF_", 1:n_f)
# Apply cPCA++ (requires geigen and corpcor packages)
# install.packages(c("geigen", "corpcor"))
if (requireNamespace("geigen", quietly = TRUE) && requireNamespace("corpcor", quietly = TRUE)) {
# Assuming helper constructors like bi_projector are available
# library(multivarious)
res_cpca_plus <- cPCAplus(X_f, X_b, ncomp = 5, method = "geigen")
# Scores for the foreground data (samples x components)
print(head(res_cpca_plus$s))
# Loadings (contrastive directions) (features x components)
print(head(res_cpca_plus$v))
}
# \donttest{
# Plot example (slow graphics)
if (requireNamespace("geigen", quietly = TRUE) && requireNamespace("corpcor", quietly = TRUE)) {
set.seed(123)
X_b <- matrix(rnorm(150 * 50), nrow=150, ncol=50)
X_f <- cbind(matrix(rnorm(100*5, sd=2), 100, 5), matrix(rnorm(100*45), 100, 45))
res <- cPCAplus(X_f, X_b, ncomp = 5, method = "geigen")
plot(res$s[, 1], res$s[, 2],
xlab = "Contrastive Component 1", ylab = "Contrastive Component 2",
main = "cPCA++ Scores")
}
# }
Run the code above in your browser using DataLab