Data Frame Manipulation in R

Instruction: Write a command to add a new column to a data frame that calculates the logarithm of an existing column 'A'.

Context: This question checks the candidate's proficiency with basic data frame operations in R. Adding computed columns is a common task in data preparation and analysis, and familiarity with such operations is crucial for efficient data handling.

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

For a numeric column, df$log_A <- log(df$A) computes the natural logarithm elementwise. Define a domain policy first.

df <- data.frame(A = c(1, exp(1), 0, -2, NA_real_)) valid <- is.finite(df$A) & df$A > 0 df$log_A <- NA_real_ df$log_A[valid] <- log(df$A[valid]) stopifnot(isTRUE(all.equal(df$log_A[1:2], c(0, 1)))) stopifnot(all(is.na(df$log_A[3:5])))...

Related Questions