Guest User

Untitled

a guest
Jan 23rd, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. A <- as.list(0:9)
  2. B <- as.list(0:9)
  3. f <- function(x, y) x^2+y
  4.  
  5. OUT <- list()
  6. for (n in 1:10) OUT[[n]] <- f(A[[n]], B[[n]])
  7. OUT
  8. [[1]]
  9. [1] 0
  10.  
  11. [[2]]
  12. [1] 2
  13.  
  14. ...
  15.  
  16. zip <- function(x, y){
  17. stopifnot(length(x)==length(y))
  18. z <- list()
  19. for (i in seq_along(x)){
  20. z[[i]] <- list(x[[i]], y[[i]])
  21. }
  22. z
  23. }
  24. E <- zip(A, B)
  25.  
  26. lapply(E, function(x) f(x[[1]], x[[2]]))
  27.  
  28. [[1]]
  29. [1] 0
  30.  
  31. [[2]]
  32. [1] 2
  33.  
  34. ...
  35.  
  36. ‘mapply’ is a multivariate version of ‘sapply’. ‘mapply’ applies
  37. ‘FUN’ to the first elements of each ... argument, the second
  38. elements, the third elements, and so on. Arguments are recycled
  39. if necessary.
  40.  
  41. OUT <- lapply(1:10, function(x) (A[[x]]^2 + B[[x]]))
  42.  
  43. OUT <- lapply(1:10, function(x) f(A[[x]], B[[x]]))
  44.  
  45. en = c("cattle", "chicken", "pig")
  46. zh = c("牛", "鸡", "猪")
  47.  
  48. dict <- new.env(hash = TRUE)
  49. Add <- function(key, val) dict[[key]] <- val
  50.  
  51. mapply(Add, en, zh)
  52. ## cattle chicken pig
  53. ## "牛" "鸡" "猪"
Add Comment
Please, Sign In to add comment