r - Index for for-loop not working well -
i have 2 dataframe
dataframe a
a 1 4 7 b b 2 5 8 c c 3 6 9
dataframe b
a 10 13 16 b b 11 14 17 c c 12 15 18
i wish create new dataframe c
retains first 2 column of a
, add corresponding numeric elements column 3 5.
i used following code:
c<-data.frame(matrix(na, nrow=3, ncol=5)) (i in 1:5) { if (i==1:2) {c[,i] <- a[,i]} else {c[,i] <- round((a[,i]+b[,i])/2,0)} } write.xlsx(c, "c.xlsx")
however, output looks follwing in excel
x1 x2 x3 x4 x5 1 #n/a 11 17 23 2 b #n/a 13 19 25 3 c #n/a 15 21 27
i think there may wrong i==1:2
part, may know how should modify code?
thank you!
this might of
a = read.table(header = f, stringsasfactors = f, text = "a 1 4 7 b b 2 5 8 c c 3 6 9") b = read.table(header = f, stringsasfactors = f, text = "a 10 13 16 b b 11 14 17 c c 12 15 18") # using loop: c = data.frame(matrix(na, nrow=3, ncol=5)) (i in 1:5) { if (i %in% 1:2) {c[,i] <- a[,i]} else {c[,i] <- round((a[,i]+b[,i])/2,0)} } # without loop: c = cbind(a[,1:2], round((a[,3:5] + b[,3:5]) / 2, 0)) print(c) # v1 v2 v3 v4 v5 # 1 6 8 12 # 2 b b 6 10 12 # 3 c c 8 10 14
Comments
Post a Comment