简体   繁体   中英

Apply function with parameters on each element of a dataframe in R

I have a dataframe with several columns. One column has entries with values that can be negative or positive. I'd like to apply a function on every entry in this column so that in case it is negative it gets set to 0 and otherwise the value should stay as it is.

my idea was the following:

df <- data.frame("ID" = c(1,2,3,4,5),"value" = c(1,-1,0,2,-2))

f <- function(value) {
  if (value > 0 ){
    return(value)
  }
  else return(0)
}

and then use something like the apply function on the "value" column of the dataframe.

eg:

df$newValue <- apply(df, f(df$value))

I'm not sure its the right approach though as I don't get it to work. Probably having a wrong understanding of "apply" as well

If you want it just for value :

df$value[df$value<0] <- 0

For a newvalue :

df$newvalue <- df$value # first copy all values
df$newvalue[df$value<0] <- 0 # change by the rule

or for all columns, you just need:

df[df<0] <- 0
#   ID value
# 1  1     1
# 2  2     0
# 3  3     0
# 4  4     2
# 5  5     0

Because df<0 will get you TRUE where that condition is met, in all columns:

df<0
        ID value
[1,] FALSE FALSE
[2,] FALSE  TRUE
[3,] FALSE FALSE
[4,] FALSE FALSE
[5,] FALSE  TRUE

You can directly use function inside sapply as lamda instead of defining it separately :

sapply(df$value,function(x){
  if (x > 0 ){
    return(x)
  }
  else return(0)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM