Explain the difference between data.frame and matrix in R.
Instruction: Discuss the structural and functional differences between a data.frame and a matrix in R.
Context: This question assesses the candidate's understanding of core data structures in R and their appropriate use cases.
Updated
Official answer available
Read the opening below, then unlock the full answer and practical guidance.
A matrix is a vector with a two-dimensional dim attribute. An ordinary atomic matrix has one underlying type; a data frame is a list of equal-row-count columns that can have different types.
df <- data.frame(id = 1:2, label = c("A", "B")) m <- as.matrix(df) stopifnot(is.integer(df$id), is.character(df$label), is.character(m)) numeric_matrix <- matrix(1:4, nrow = 2) stopifnot(identical(dim(numeric_matrix...