dataframe - Apply a list for 3 ways frequency table in R -


this question has answer here:

i have 3 ways frequency table, want combine them list, write listoftable <- list(table[,,1],table[,,2],table[,,3],table[,,4],table[,,5]), table long, there way can apply lapply combine list without doing manually.

df <- data.frame(id = c(rep(c("a","b","c"),5)),              n = c(rep(c("1","2","3"),5)),              m = c(rep(1,3),rep(2,3),rep(3,3),rep(4,3),rep(5,3))) applyalist <- table(df$id,df$n,df$m) listoftable <- list(applyalist[,,1],applyalist[,,2],applyalist[,,3],applyalist[,,4],applyalist[,,5]) 

we can lapply looping through sequence of third dimension , subsetting 'applyalist' based on sequence.

lapply(seq(dim(applyalist)[3]), function(i) applyalist[,,i]) 

as op wants list output, lapply gives output. sapply, default option simplify = true return matrix or vector when length of elements same in case did not change option simplify = false. in cases list elements of different classes, become more noticeable , damaging.

lst <- list(a = 1:3, b = rep(letters[1:3], 2), c = 2:4) lapply(lst, unique) #$a #[1] 1 2 3  #$b #[1] "a" "b" "c"  #$c #[1] 2 3 4  sapply(lst, unique) #        b   c   #[1,] "1" "a" "2" #[2,] "2" "b" "3" #[3,] "3" "c" "4" 

but,

sapply(lst, unique, simplify = false) #$a #[1] 1 2 3  #$b #[1] "a" "b" "c"  #$c #[1] 2 3 4 

gives similar results lapply changed simplify


Comments

Popular posts from this blog

loops - Spock: How to use test data with @Stepwise -

amazon web services - S3 Pre-signed POST validate file type? -