Quantcast
Viewing all articles
Browse latest Browse all 206316

R nested for-loop only producing result with last column in dataframe

CONTEXT:

  • I'm working with respondent-level survey data. Each row of my data frame represents an individual person's survey responses.
  • My data frame consists of individual-level utility estimates from a Maximum Difference experiment AND categorical variables indicating in which of several subgroups an individual survey respondent resides.
  • Each subgroup variable is a single categorical variable with exactly two levels. However, in my desired output, I'd like a data frame where each level of each subgroup has its own column.

OBJECTIVE:

  • I want to create a function that, for each user-defined subgroup, will conduct recursive T Tests over every Maximum Difference item in the data frame, extract elements of the T Test output, and store the elements in a data frame

    - Using T statistic results as an example, the end result should look like this:

         Males_T_stat     Females_T_stat
MD_item1      2.71              2.5
MD_item2      1.71              1.5
MD_item3      0.71              0.5

CURRENT CODE:

  • Right now, I'm focused on writing code to iteratively execute the T Tests and store each test's entire output object in a list. The code I've used to, unsuccessfully, attempt this is below:

Create a test data frame:

dat <- data.frame(
  md1 = 1:60, 
  gender = factor(rep(c("m", "f"), 30)), 
  generation = factor(rep(c("a", "b"), 30)),
  md2 = 61:120
)

Specify the names of my respondent subgroup (i.e., the categorical variables).

groupnames <- c("gender", "generation")

item_vec <- dat %>% select(contains(("md")))
group_vec <- dat[groupnames]

Convert the subgroup name vectors to data frames. this step may be superfluous, but I'm more comfortable working with data frames.

item_vec <- data.frame(item_vec)
group_vec <- data.frame(group_vec)

So far, I've tried using nested for loops to run the T Tests and store each test output in a list. This code partially works; for each subgroup named in "group_vec", the code produces T Test results for the last item in "item_vec" only. However, I want the results for EVERY item in "item_vec", which is where I've currently stalled.

res <- list()

   for (i in 1:length(group_vec)) {
     res[[i]] <- list(test)
      for (j in 1:length(item_vec)) {
        test <- (t.test(item_vec[[j]] ~ group_vec[[i]])) 
        res[i] <- list(test)
      }
   }

 res

Thank you in advance for any help you can provide!


Viewing all articles
Browse latest Browse all 206316

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>