Skip to content

Instantly share code, notes, and snippets.

@saraswatmks
Created January 6, 2018 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saraswatmks/f5745e877e34b362341785b90ca2c0fa to your computer and use it in GitHub Desktop.
Save saraswatmks/f5745e877e34b362341785b90ca2c0fa to your computer and use it in GitHub Desktop.
split to multiple columns in R
check1 <- data.table(name = c('a,b','a,b,c','a,b,d','b,d,e','e,f,g','a,b,f'))
to_columns <- function(df, col_name)
{
get_values <- unique(unlist(strsplit(df[[col_name]], split = ",")))
d <- strsplit(df[[col_name]], split = ",")
for(i in get_values)
{
df[[paste0("col_",i)]] <- sapply(d, function(x) as.integer(i %in% x))
}
return(df)
}
check1 <- to_columns(check1, "name")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment