subset lists based on a condition in r -


i have data frame looks like:

df = read.table(text="s00001    s00002  s00003  s00004  s00005  s00006   gg  aa  gg  aa  gg  ag   cc  tt  tt  tc  tc  tt   tt  cc  cc  tt  tt  tt   aa  aa  gg  aa  ag  aa   tt  cc  cc  tt  tc  tt   gg  gg  gg  aa  gg  gg", header=t, stringsasfactors=f) 

i count number of character strings same letters (i.e. "aa", "cc", "gg", or "tt") each row. did use table() function count elements , generated list based on if names of lists "homo". tried subset lists didn't work. here scripts:

a <- apply(df,1, function(x) table(x)) b <- apply(df,1, function(x) (names(table(x)) %in% c("aa","cc","gg","tt"))) a[b] ## didn't work 

i expect data frame generated:

2 3 1 3 2 4 4 1 2 3 1 5 

appreciate helps.

we single apply

t(apply(df, 1, function(x) {tbl <- table(x)         tbl[names(tbl) %in% c("aa", "cc", "gg", "tt")]})) #      [,1] [,2] #[1,]    2    3 #[2,]    1    3 #[3,]    2    4 #[4,]    4    1 #[5,]    2    3 #[6,]    1    5 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -