问题
I'm working with the following data:
#Reproducible Example
Bills <- c("93-HCONRES-106", "93-HCONRES-107", "93-HCONRES-108")
Members <- c("00134", "00416;00010;00017;00026", "00416;00503;00513;00568")
data <- data.frame(Bills, Members)
Where the data looks like this:
#Data Structure
Bills Members
1 93-HCONRES-106 00134
2 93-HCONRES-107 00416;00010;00017;00026
3 93-HCONRES-108 00416;00503;00513;00568
What I would like is for the dataset to extend, such that each bill corresponds with each member. So the data looks like this:
Bills Members
93-HCONRES-106 00134
93-HCONRES-107 00416
93-HCONRES-107 00010
93-HCONRES-107 00017
93-HCONRES-107 00026
93-HCONRES-108 00416
93-HCONRES-108 00503
93-HCONRES-108 00513
93-HCONRES-108 00568
Any code you could share would be greatly appreciated.
Thanks so much for all your help
回答1:
We can use separate_rows
from tidyr
library(dplyr)
library(tidyr)
data %>%
separate_rows(Members)
# Bills Members
#1 93-HCONRES-106 00134
#2 93-HCONRES-107 00416
#3 93-HCONRES-107 00010
#4 93-HCONRES-107 00017
#5 93-HCONRES-107 00026
#6 93-HCONRES-108 00416
#7 93-HCONRES-108 00503
#8 93-HCONRES-108 00513
#9 93-HCONRES-108 00568
Or extract the elements into a list
and then unnest
library(stringr)
data %>%
mutate(Members = str_extract_all(Members, "[^;]+")) %>%
unnest(c(Members))
Or with base R
stack(setNames(strsplit(as.character(data$Members), ";"), data$Bills))
回答2:
Using data.table:
library(data.table)
dt1 <- data.table(Bills, Members)
dt2 <- melt(dt1[, c("V1", "V2", "V3", "V4") := tstrsplit(Members, ";")][, Members := NULL], id.vars = "Bills")[!is.na(value)][order(Bills)]
来源:https://stackoverflow.com/questions/60841927/how-to-further-melt-a-dataset