Home > Enterprise >  How to create a nested for loop using dataframe and vector as 2 sets of values?
How to create a nested for loop using dataframe and vector as 2 sets of values?

Time:10-11

Here I have 6 columns with 3 values in each so 3 rows

 ob1 <- rep(1,3)
 ob2 <- rep(2,3)
 ob3 <-rep(3,3)
 ob4 <- rep(4,3)
 ob5 <- rep(5,3)
 ob6 <- rep(6,3)

 df <- data.frame(ob1,ob2,ob3,ob4,ob5,ob6)

 df
  ob1 ob2 ob3 ob4 ob5 ob6
   1   1   2   3   4   5   6
   2   1   2   3   4   5   6
   3   1   2   3   4   5   6

This value vector will always have the length equal to # of rows in DF

  value <- c(1.9,2.3,4.5)

I want to be able to loop through DF rows and index of value (i and j) so I don't have to manually create test multiple times (in this example, for the 3 rows)

df[1,] specifies the row and value[1] is the first element in vector so they match in length

 test <- sum((df[1,]-value[1])**2) / 6
 test
 5.4766

There should be 3 test values because 3 rows, how do I loop?

CodePudding user response:

Using the Idea from @Rui Barradas You could do:

rowMeans((df - value)^2)
[1] 5.476667 4.356667 3.916667
  • Related