kdestasio kdestasio - 3 years ago 175
R Question

R - How to iteratively change values in columns based on

I have a data frame with 10 variables. For each column of variables 1-9, I would like to replace the values with

NA
if the tenth variable in that row is
NA
.

Before doing anything, the data looks like this:

var1 var2 var3 ... var10
1 3 3 2
0 0 0 NA
9 3 7 4
0 0 0 NA
. . . .
. . . .
. . . .


The goal is for the data to look like this:

var1 var2 var3 ... var10
1 3 3 2
NA NA NA NA
9 3 7 4
NA NA NA NA
. . . .
. . . .
. . . .


The code I am using is the following, run once for each variable 1-9:

data <- data %>%
mutate(var1= replace(var1, # var1 on this line would be replaced by var2, var3, etc.
which(is.na(var10)), NA))


However, I'm sure there's a better way to do this than copy/pasting that code 9 times, once for each variable 1-9.

I'm relatively new to coding in general. It seems like something based on this post is applicable, but have not found a way to make it work. Any solutions are greatly appreciated!

Answer Source

If we are using dplyr, then mutate_at can be used

data %>%
    mutate_at(1:9, funs(replace(., is.na(data$var10), NA)))

Or we can use purrr

library(purrr)
map2_df(data[1:9], data[10], ~replace(.x, is.na(.y), NA))

This can be also done with base R

data[1:9] <- data[1:9]*NA^is.na(data$var10)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download