Home > Back-end >  for loop: dataframe * vector operation
for loop: dataframe * vector operation

Time:04-30

I want to make some operations on my dataframe by multiplying cells value to a vector.

mydat <- dataframe(
type = rep("a", "b", "c", "d"),
site.a = c(10, 2.5,5,4),
site.b = c(6, 3, 7, 3.1),
site.c = c(2, 2.4, 6, 7),
site.d = c(9, 6, 7.2, 4.2))

I would like to multiply each column in order by the following vector

wall <- c(10.4, 11, 12, 13.5)

i.e I would like to have a for loop for the following: mydat[2]*wall[1], site.b*wall[2], etc... until mydat[n 1]*wall[n]

I tried to following code but I doesn't work, It said the following error "unexpected "{" in "}"

while (i < 8) {
  for i in (1:8) {
    mydat[i 1] = mydat[i 1]/wall[i]
  }
}

Can anyone help me? I am just beginning how to code and I am not familiar with looping

CodePudding user response:

I just found the solution. The answer is actually shorter that I thought.

for (i in 1:4){
  mydat2[,i 1] <-  mydat[,i 1]/wall[i]
}

CodePudding user response:

Consider no loops with matrix operations by expanding the wall vector to matrix of same size as mydat. Below assumes columns will be same between both objects:

wall_m <- matrix(wall, ncol=length(wall), nrow=nrow(mydat), byrow=TRUE)

mydat2[-1] <- mydat2[-1] / wall_m

Above approach yields identical results:

mydat <- data.frame(
  type = c("a", "b", "c", "d"),
  site.a = c(10, 2.5,5,4),
  site.b = c(6, 3, 7, 3.1),
  site.c = c(2, 2.4, 6, 7),
  site.d = c(9, 6, 7.2, 4.2)
)
mydat2 <- mydat

wall <- c(10.4, 11, 12, 13.5)

# LOOP VERSION
for(i in (1:4)) {
  mydat[i 1] = mydat[i 1]/wall[i]
}

# MATRIX VERSION
wall_m <- matrix(wall, ncol=length(wall), nrow=nrow(mydat2), byrow=TRUE)
mydat2[-1] <- mydat2[-1] / wall_m

identical(mydat, mydat2)
[1] TRUE
  • Related