Skip to content

Instantly share code, notes, and snippets.

@Ze1598
Created July 14, 2020 12:04
Show Gist options
  • Save Ze1598/423b0ca90b6bdcd1fcd54582236966a8 to your computer and use it in GitHub Desktop.
Save Ze1598/423b0ca90b6bdcd1fcd54582236966a8 to your computer and use it in GitHub Desktop.
Unpivot data with delimiters (R): split and unpivot
library(readr)
library(dplyr)
library(plotly)
library(tidyr)
library(stringr)
data <- read_csv("sample_data.csv")
max_split_cols <- max(mapply(str_count, data$`Used Social Networks`, ";"), na.rm = TRUE) + 1
sep_into_cols <- unname(mapply(paste, "Col", 1:max_split_cols, sep = ""))
# Split the individual values of each row into their own column
separated_data <- data %>%
separate(`Used Social Networks`, sep_into_cols, sep = ";", fill = "right")
# Unpivot the columns of individual options into a single column
# Column names go into "TempCols", values go into "Used Social Networks"
unpivot_wide_data <- separated_data %>%
pivot_longer(
sep_into_cols,
names_to = "TempCols",
values_to = "Used Social Networks",
values_drop_na = TRUE
)
# Remove the column with the names of the temporary columns
unpivot_wide_data <- unpivot_wide_data %>%
select(-TempCols)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment