Reputation: 15
replace.value(zdata, c(1), DL[1], 0)
replace.value(zdata, c(2), DL[2], 0)
replace.value(zdata, c(3), DL[3], 0)
replace.value(zdata, c(4), DL[4], 0)
replace.value(zdata, c(5), DL[5], 0)
replace.value(zdata, c(6), DL[6], 0)
replace.value(zdata, c(7), DL[7], 0)
replace.value(zdata, c(8), DL[8], 0)
I need to change a specific value (which are given in the DL vector) with 0 for each column of the data frame. For example the first value of the DL vector is 0.5 so the first line of the code above changes every 0.5 in the first column of the data frame to 0.
Upvotes: 0
Views: 52
Reputation: 145870
Yes. Let's make some improvements. First of all, c()
stands for concatenate, which means to "stick things together". If you only have one thing, you don't need c()
. 5
is the same as c(5)
, "hello"
is the same as c("hello")
, etc.
A for
loop lets you loop over specific values. The values you change in each line of code go from 1 to 8, so we'll loop over that:
for (val in 1:8) {
replace.value(zdata, val, DL[val], 0)
}
I don't know the replace.value
function (and you don't mention what package it's in), but it seem strange that you aren't assigning the results. In base R, you'd do something like this:
zdata[1][zdata[1] == DL[1]] <- 0
zdata[2][zdata[2] == DL[2]] <- 0
...
Using <-
to assign the result so it is saved. That would turn into this for loop:
for (val in 1:8) {
zdata[val][zdata[val] == DL[val]] <- 0
}
Upvotes: 2
Reputation: 5405
If you want to use the tidyverse
more explicitly, you can use something like walk
library(tidyverse)
walk(1:8, ~replace.value(zdata, .x, DL[.x], 0))
Upvotes: 0