Merging dataframes that are outputs from a for loop in r -



Merging dataframes that are outputs from a for loop in r -

i have big dataframe (only showing first 3 columns):

dataframe called chr22_hap12

2 1 3 2 1 3 2 1 3 2 1 2 2 2 1 2 2 1

i proportion of each number (ones, twos , threes in order) every column , store in dataframe.

this have far:

for (i in 1:3 ) { length(chr22_hap12[,i]) -> total_snps sum(chr22_hap12[,i]==1,na.rm=false) -> counts_ancestry_1 sum(chr22_hap12[,i]==2,na.rm=false) -> counts_ancestry_2 sum(chr22_hap12[,i]==3,na.rm=false) -> counts_ancestry_3 (counts_ancestry_1*100)/total_snps -> ancestry_1_perc (counts_ancestry_2*100)/total_snps -> ancestry_2_perc (counts_ancestry_3*100)/total_snps -> ancestry_3_perc haplo_df[i] = null haplo_df[i] = c(ancestry_1_perc,ancestry_2_perc,ancestry_3_perc) as.data.frame(haplo_df[i]) }

i these erros: after trying set haplo_df[i] = null

error in haplo_df[i] = null : object 'haplo_df' not found

and after

haplo_df[i] = c(ancestry_1_perc,ancestry_2_perc,ancestry_3_perc)

error in haplo_df[i] = c(ancestry_1_perc, ancestry_2_perc, ancestry_3_perc) : object 'haplo_df' not found

and 1 time again as.data.frame(haplo_df[i])

object 'haplo_df' not found

my want output should this:

0.00 66.66 50.0 100.00 33.33 33.33 0.00 0.00 16.66

you need define resulting matrix before loop , cbind new result matrix.

# define data.frame before loop. haplo_df <- null (i in 1:3 ) { length(chr22_hap12[,i]) -> total_snps sum(chr22_hap12[,i]==1,na.rm=false) -> counts_ancestry_1 sum(chr22_hap12[,i]==2,na.rm=false) -> counts_ancestry_2 sum(chr22_hap12[,i]==3,na.rm=false) -> counts_ancestry_3 (counts_ancestry_1*100)/total_snps -> ancestry_1_perc (counts_ancestry_2*100)/total_snps -> ancestry_2_perc (counts_ancestry_3*100)/total_snps -> ancestry_3_perc # bind new result existing info haplo_df <- cbind(haplo_df , c(ancestry_1_perc,ancestry_2_perc,ancestry_3_perc)) } # homecoming result haplo_df ## [,1] [,2] [,3] ## [1,] 0 66.66667 33.33333 ## [2,] 100 33.33333 16.66667 ## [3,] 0 0.00000 50.00000

instead utilize apply , table, e.g.

apply(chr22_hap12, 2, function(x) 100*table(factor(x, levels=1:3))/length(x)) ## v1 v2 v3 ## 1 0 66.66667 33.33333 ## 2 100 33.33333 16.66667 ## 3 0 0.00000 50.00000

r

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -