Skip to content

Instantly share code, notes, and snippets.

@awalsh17
Created March 7, 2022 16:59
Show Gist options
  • Save awalsh17/211c9fde41b0d2411a1d5fb61fd78e40 to your computer and use it in GitHub Desktop.
Save awalsh17/211c9fde41b0d2411a1d5fb61fd78e40 to your computer and use it in GitHub Desktop.
I forget about stack and unstack
# something interesting in R
# `stack` function
# Stacking vectors concatenates multiple vectors into a single vector along
# with a factor indicating where each observation originated. Unstacking
# reverses this operation.
a_list <- list(group1 = letters[1:5],
group2 = letters[6:10],
group3 = letters[11:15])
stack(a_list)
# values ind
# 1 a group1
# 2 b group1
# 3 c group1
# 4 d group1
# 5 e group1
# 6 f group2
# 7 g group2
# 8 h group2
# 9 i group2
# 10 j group2
# 11 k group3
# 12 l group3
# 13 m group3
# 14 n group3
# 15 o group3
# if you table() the result from stack(), now you have a nice matrix
# of the values in each group
table(stack(a_list))
# this is a table. You can convert to a data.frame
as.data.frame.array(table(stack(a_list)))
# you can also convert the binary matrix to logical TRUE/FALSE
table(stack(a_list)) > 0
# imagine a case where you have the table and some values are greater than 1
# you can use that trick to convert to logical and back to numeric 0/1
b_list <- list(group1 = rep(letters[1],5),
group2 = letters[6:10],
group3 = letters[11:15])
table(stack(b_list))
+(table(stack(b_list)) > 0)
# ind
# values group1 group2 group3
# a 1 0 0
# f 0 1 0
# g 0 1 0
# h 0 1 0
# i 0 1 0
# j 0 1 0
# k 0 0 1
# l 0 0 1
# m 0 0 1
# n 0 0 1
# o 0 0 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment