[R] Replicating Rows

arun smartpink111 at yahoo.com
Fri Jul 12 14:42:47 CEST 2013


Hi,

apple<- read.table(text="
Fam.name,Item,AMT.SALE.NET.PROMO,X.CY..QTY.SALE.TOT
9475,Imported Fruits,22110276001,0,436
9499,Imported Fruits,22110277001,0,236
9523,Imported Fruits,22110278001,0,71 
",sep=",",header=TRUE,stringsAsFactors=FALSE)
str(apple)
#'data.frame':    3 obs. of  4 variables:
# $ Fam.name          : chr  "Imported Fruits" "Imported Fruits" "Imported Fruits"
# $ Item              : num  2.21e+10 2.21e+10 2.21e+10
# $ AMT.SALE.NET.PROMO: int  0 0 0
# $ X.CY..QTY.SALE.TOT: num  436 236 71

Here, it changed the class of some of the variables.
new<-sapply(apple[,-4],rep,apple[,4]) 
str(as.data.frame(new,stringsAsFactors=FALSE))
#'data.frame':    743 obs. of  3 variables:
# $ Fam.name          : chr  "Imported Fruits" "Imported Fruits" "Imported Fruits" "Imported Fruits" ...
# $ Item              : chr  "22110276001" "22110276001" "22110276001" "22110276001" ...
# $ AMT.SALE.NET.PROMO: chr  "0" "0" "0" "0" ...



new1<-apple[rep(seq_len(nrow(apple)),apple[,4]),-4]
 row.names(new1)<- 1:nrow(new1)
 str(new1)
#'data.frame':    743 obs. of  3 variables:
# $ Fam.name          : chr  "Imported Fruits" "Imported Fruits" "Imported Fruits" "Imported Fruits" ...
# $ Item              : num  2.21e+10 2.21e+10 2.21e+10 2.21e+10 2.21e+10 ...
# $ AMT.SALE.NET.PROMO: int  0 0 0 0 0 0 0 0 0 0 ..
A.K.




I try to replicate the rows according to the number of quantity 
occurred. Its row should be be sum of the quantity. is there any wrong 
with my code? thanks. 

apple 
            Fam.name        Item AMT.SALE.NET.PROMO X.CY..QTY.SALE.TOT 
9475 Imported Fruits 22110276001                  0                436 
9499 Imported Fruits 22110277001                  0                236 
9523 Imported Fruits 22110278001                  0                 71 
9552 Imported Fruits 22110306001                  0                 69 
9571 Imported Fruits 22110314001                  0                 20 
9579 Imported Fruits 22110315001                  0                 80 
9604 Imported Fruits 22110317001                  0                 61 
9635 Imported Fruits 22110321001                  0               1026 
9697 Imported Fruits 22110334001                  0                223 
9720 Imported Fruits 22110335001                  0                214 
9744 Imported Fruits 22110336001                  0                102 
9768 Imported Fruits 22110337001                  0                146 
9868 Imported Fruits 22110354001              118.8                 17 
9893 Imported Fruits 22110360001                  0                 43 
9904 Imported Fruits 22110363001                  0                 49 
9920 Imported Fruits 22110364001                  0                  1 
9938 Imported Fruits 22110365001              205.4                 33 

new<-sapply(apple[,-4],rep,apple[,4]) 
nrow(new) 
[1] 33572



More information about the R-help mailing list