0
votes

Can someone provide suggestions on creating a new table column from another vector in R?

I have a table named "main" with test types and number of tests. I want to create a new column to assign the test values.

Test Type    Number of Tests    Test Value
    a               1               
    b               4   
    c               3
    d               2

The test value is stored in an order in another vector x <- (0.1, 0.2, 0.2, 0.3, 0.2, 0.6, 0.5, 0.6, 1.2, 1.3). The total number of test values in the vector equals the total number of tests performed.

The test value for corresponding test type equals the mean of values of the multiple tests. For example, test a type is 0.1, test b type is (0.2+0.2+0.3+0.2)/4, test c type is (0.6+0.5+0.6)/3, test d type is (1.2+1.3)/2.

Following are my code:

idx_low <- 1
number_vector <- numeric()
for (value in main[[2]]) {
    idx_high <- idx_low+value-1
    number <- mean(x[idx_low:idx_high])
    number_vector <- c(number_vector, number)
    idx_low <- idx_high+1
}
main[[3]] <- number_vector  
1

1 Answers

0
votes

How about this:

library("dplyr")
main = data.frame(test_type = letters[1:4],
                  num_tests = c(1,4,3,2),
                  stringsAsFactors = FALSE)
test_scores = c(0.1, 0.2, 0.2, 0.3, 0.2, 0.6, 0.5, 0.6, 1.2, 1.3)
labels = c()
for(i in 1:nrow(main)){
  labels = c(labels, rep(x = main$test_type[i], times = main$num_tests[i] ))
}

test_scores = data.frame(scores = test_scores,
                         test_type = labels) %>% 
  group_by(test_type) %>% 
  summarise(avg_score = mean(scores)) %>% 
  right_join(main)