'unwind' R function

Unwind R function
Unwind R function

While working on Yelp's 'users' dataset, I needed to 'unwind' the list of friends that each user has, append it to the user itself (thus creating two rows, one with user_id and one with the list of friends) and then rbind for each user.

The idea of the 'unwind' function is taken from MongoDB, where it is a build-it one.
The need to unwind is quite common when working with JSON objects, since having arrays embedded in documents is common usage.

The function worked quite fast and efficiently for me.

Below is the function's code

unwind <- function(df,col1,col2,idx){
unwinded_column <- unlist(df[idx,col2])
unwinded_list <- data.frame()
unwinded_list <- data.frame(cbind(df[idx,col1],unwinded_column))
if ( (dim(unwinded_list)[2]) == 2){
names(unwinded_list) <- c(col1,col2)
} else{
unwinded_list <- data.frame()
}
return (unwinded_list) }

Input explanation:
df = the whole dataframe
col1 = key column
col2 = list column
row number in the dataframe (since this function is performed in a loop)

Example:
unwind(users'user_id''friends',i)

Enjoy it...