0

Very simple problem I'm trying to solve, just can't seem to figure it out. I want to apply a certain criteria which is in a column to a number of columns.

cols_to_change<-['d','e','f']

for one column, d, i can do this:

df$d[which(df$criteria<df$d)]<-NA

But for the other columns,e,f, I could do a for loop, but I wanted to use an apply function instead. How can I do this?

Ric S
  • 9,073
  • 3
  • 25
  • 51
simonsays
  • 61
  • 5

1 Answers1

2

Without sample data it is difficult to validate what you are trying to do. Anyways, I think you are looking for something like the following

cols_to_change <- c("d", "e", "f")
df[cols_to_change] <- lapply(df[cols_to_change], function(x) ifelse(df$criteria < x, NA, x))

Note that lapply is a preferred version with respect to apply.

Ric S
  • 9,073
  • 3
  • 25
  • 51
  • thanks, this is exactly what i was after. I need to learn how to use this functions, it's quite confusing for me! – simonsays Jul 30 '20 at 12:38
  • 1
    Just have a look at the documentation and practice, it's the most efficient way to learn :) – Ric S Jul 30 '20 at 12:49