David B
David B

Reputation: 25

Removing one data element (value) at a time from variable and performing function in R

I am attempting to write code in R that permits me to:

  1. Remove the first data element (value) from a variable (column) within a larger data frame.

  2. Run a function on the full data frame (with the data element from step 1 removed).

  3. Repeat this process for the remaining data elements in the column.

I've tried the following code and have run it without receiving errors. However, it is clear from the results that the data elements are not being successively removed as desired.

For context, my data frame (df) is 50x18 and the function that I am attempting to run from step 2 is a multiple imputation function. Here is my code:

procedure <- function(x) {
  x <- NA
  mice(df, m = 5, maxit = 5, method = "norm", pred = pred_matrix, seed = 2019)
}

results <- lapply(df$variable, procedure)

As desired, this code produces a list with 50 sets of output. However, it appears to perform the procedure 50 times on the same exact data frame. Thus, my question: Why isn't my code looping through each element in the data variable and removing it before running the procedure? I am not trying to shrink the data frame (remove a row). Instead, for each value (x) in the variable, I want to make the value "NA" (go missing) and then execute the procedure.

Thanks in advance!

Upvotes: 1

Views: 53

Answers (1)

GordonShumway
GordonShumway

Reputation: 2056

Assuming that the elements of df$variable are unique the following should work:

procedure <- function(x) {
  df1 <- df
  df1[df1$variable == x,"variable"] <- NA
  mice(df1, m = 5, maxit = 5, method = "norm", pred = pred_matrix, seed = 2019)
}

results <- lapply(df$variable, procedure)

If they are not unique you can loop over the indices as follows:

procedure <- function(x) {
  df1 <- df
  df1[x,"variable"] <- NA
  mice(df1, m = 5, maxit = 5, method = "norm", pred = pred_matrix, seed = 2019)
}

results <- lapply(1:length(df$variable), procedure)

Upvotes: 1

Related Questions