Guest User

Untitled

a guest
Aug 16th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.54 KB | None | 0 0
  1. Replace values in selected columns by passing column name of data.frame into apply() or plyr function
  2. df <- data.frame(a=1:5, b=sample(1:5, 5, replace=TRUE), c=5:1)
  3. df
  4. a b c
  5. 1 1 4 5
  6. 2 2 3 4
  7. 3 3 5 3
  8. 4 4 2 2
  9. 5 5 1 1
  10.  
  11. df
  12. a b c
  13. 1 1 4 NA
  14. 2 2 3 4
  15. 3 3 NA 3
  16. 4 4 2 2
  17. 5 5 1 1
  18.  
  19. var <- c("b", "c")
  20.  
  21. df <- within(df, sapply(var, function(x) x <- replace(x, x==5, NA)))
  22.  
  23. df <- data.frame(a=1:5, b=sample(1:5, 5, replace=TRUE), c=5:1)
  24. df
  25. var <- c("b","c")
  26. df[,var] <- sapply(df[,var],function(x) ifelse(x==5,NA,x))
  27. df
  28.  
  29. df[,var][df[,var] == 5] <- NA
Add Comment
Please, Sign In to add comment