Guest User

Untitled

a guest
Dec 12th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. A B C
  2. A B C 1 j i 100
  3. 1 j i 100 --> 2 j i 100
  4. 2 K P 101 3 K P 101
  5. 4 K P 101
  6.  
  7. A B C
  8. [1,] "j" "i" "100"
  9. [2,] "j" "i" "100"
  10. [3,] "K" "P" "101"
  11. [4,] "K" "P" "101"
  12.  
  13. df <- data.frame(a=1:2, b=letters[1:2])
  14. df[rep(seq_len(nrow(df)), each=2),]
  15.  
  16. library(plyr)
  17. rep.row <- function(r, n){
  18. colwise(function(x) rep(x, n))(r)
  19. }
  20.  
  21. library(mefa)
  22. rep(mtcars,10)
  23.  
  24. mefa:::rep.data.frame(mtcars)
  25.  
  26. rep(df, each=N)
  27.  
  28. rep(df, times=N)
  29.  
  30. > data <- data.frame(a=letters[1:3], b=letters[4:6])
  31. > data
  32. a b
  33. 1 a d
  34. 2 b e
  35. 3 c f
  36. > as.data.frame(lapply(data, rep, 2))
  37. a b
  38. 1 a d
  39. 2 b e
  40. 3 c f
  41. 4 a d
  42. 5 b e
  43. 6 c f
  44.  
  45. N=2
  46. rep(1:4, each = N)
  47.  
  48. rep.data.frame <- function(x, times) {
  49. rnames <- attr(x, "row.names")
  50. x <- lapply(x, rep.int, times = times)
  51. class(x) <- "data.frame"
  52. if (!is.numeric(rnames))
  53. attr(x, "row.names") <- make.unique(rep.int(rnames, times))
  54. else
  55. attr(x, "row.names") <- .set_row_names(length(rnames) * times)
  56. x
  57. }
  58.  
  59. library(Lahman)
  60. library(microbenchmark)
  61. microbenchmark(
  62. mefa:::rep.data.frame(Batting, 10),
  63. rep.data.frame(Batting, 10),
  64. Batting[rep.int(seq_len(nrow(Batting)), 10), ],
  65. times = 10
  66. )
  67. #> Unit: milliseconds
  68. #> expr min lq mean median uq max neval cld
  69. #> mefa:::rep.data.frame(Batting, 10) 127.77786 135.3480 198.0240 148.1749 278.1066 356.3210 10 a
  70. #> rep.data.frame(Batting, 10) 79.70335 82.8165 134.0974 87.2587 191.1713 307.4567 10 a
  71. #> Batting[rep.int(seq_len(nrow(Batting)), 10), ] 895.73750 922.7059 981.8891 956.3463 1018.2411 1127.3927 10 b
  72.  
  73. df$index = 1:nrow(df)
  74. df = rbind(df,df)
  75. df = df[order(df$index),][,-ncol(df)]
  76.  
  77. library(dplyr)
  78. df <- data_frame(x = 1:2, y = c("a", "b"))
  79. df %>% slice(rep(1:n(), each = 2))
Add Comment
Please, Sign In to add comment