Home > database >  Counter in if...else statement in R to fill vector?
Counter in if...else statement in R to fill vector?

Time:01-06

I am trying to fill a vector of length 4 using simple calculations that rely on numbers from another table. The rightmost column "nrow" is the sum of the rows in table 4.1. Table6.row is a vector representing the number of elements in a row name: 99=0, a, b, and d all =1, bd=2, abd=3. I want to fill goalvector[1] with the quotient of table4.1[1, "nrow"] and N. goalvector[2] would be filled with the quotient of the sum of table4.1[2:4, "nrow"] and N, since rows 2:4 of table4.1 all represent single elements (a, b, and d). Below is my reproducible example:

table6.row <- c(0,1,1,1,2,3)
table4.1 <- matrix(data=c(0,0,0,1,1,0,0,0,1,0,1,1,1,2,0,0,0,0,0,0,0,0,0,0,1,2,1,1,2,1), nrow=6, ncol=5)
colnames(table4.1) <- c("U1", "U2", "U3", "U4", "nrow") 
rownames(table4.1) <- c("99", "a", "b", "d", "bd", "abd")

Below is the loop with the if...else statements I'm trying to run to ultimately create the vector at the end (goalvector).

goalvector <- numeric()
n.card <- 0
P <- 1
N <- 8
for (i in ncol(table4.1)) {
  if(table6.row[i]==0) {
      n.card <- table4.1[i, "nrow"]
  } else if(table6.row[i]==table6.row[i-1]) {
      n.card <- n.card   table4.1[i, "nrow"]
  } else {
      goalvector[P] <- n.card/N
      n.card <- 0
      P <- P 1
      n.card <- table4.1[i,"nrow"]
  }
}

The output I want:

goalvector <- c(.125, .5, .25, .125)

Where goalvector[1] is equal to .125 or 1/8, the quotient of table4.1[1,"nrow"] and N. goalvector[2] is equal to 0.5 or 4/8, which is the sum of table4.1[2:4, "nrow"] over N, because rows 2:4 of table4.1[,"nrow"] all represent rows with a single element in their rowname (a, b, and d). goalvector[3] is equal to 0.25 or 2/8, the quotient of table4.1[5, "nrow"] and N because this is the only row representing two elements (bd).

CodePudding user response:

As far as I can understand, you want to sum up values in table4.1[, "nrow"] by values in table6.row. Then, divide that sum by N, which is 8 in this case. You can do that with the function aggregate in base R.

N <- 8
goalvector <- aggregate(x ~ y, data.frame(x = table4.1[, "nrow"], y = table6.row), sum)$x / N
goalvector

Output

[1] 0.125 0.500 0.250 0.125
  •  Tags:  
  • Related