Replace values in selected columns by passing column name of data.frame into apply() or plyr function

前端 未结 2 593
萌比男神i
萌比男神i 2021-01-03 12:23

Suppose I have a date.frame like:

df <- data.frame(a=1:5, b=sample(1:5, 5, replace=TRUE), c=5:1)
df
  a b c
1 1 4 5
2 2 3 4
3 3 5 3
4 4 2 2
5 5 1 1


        
相关标签:
2条回答
  • 2021-01-03 12:39
    df <- data.frame(a=1:5, b=sample(1:5, 5, replace=TRUE), c=5:1)
    df
    var <- c("b","c")
    df[,var] <- sapply(df[,var],function(x) ifelse(x==5,NA,x))
    df
    

    I find the ifelse notation easier to understand here, but most Rers would probably use indexing instead.

    0 讨论(0)
  • 2021-01-03 12:53

    You could just do

    df[,var][df[,var] == 5] <- NA
    
    0 讨论(0)
提交回复
热议问题