R: Split unbalanced list in data.frame column

时光毁灭记忆、已成空白 提交于 2019-11-26 11:36:27

问题


Suppose you have a data frame with the following structure:

df <- data.frame(a=c(1,2,3,4), b=c(\"job1;job2\", \"job1a\", \"job4;job5;job6\", \"job9;job10;job11\"))

where the column b is a semicolon-delimited list (unbalanced by row). The ideal data.frame would be:

id,job,jobNum
1,job1,1
1,job2,2
...
3,job6,3
4,job9,1
4,job10,2
4,job11,3

I have a partial solution that takes almost 2 hours (170K rows):

# Split the column by the semicolon.  Results in a list.
df$allJobs <- strsplit(df$b, \";\", fixed=TRUE)

# Function to reshape column that is a list as a data.frame
simpleStack <- function(data){
    start <- as.data.frame.list(data)                       
    names(start) <-c(\"id\", \"job\")
    return(start)
}
# pylr!
system.time(df2 <- ddply(df, .(id), simpleStack))

It appears to be a size issue, because if I run

system.time(df2 <- ddply(df[1:4000,c(\"id\", \"allJobs\")], .(id), simpleStack))

it only takes 9 seconds. First converting to a set of data.frames with sapply (with a different function) is fast, but the required `rbind\' takes even longer.


回答1:


#Split by ; as before
allJobs <- strsplit(df$b, ";", fixed=TRUE)

#Replicate a by the number of jobs in each case
n <- sapply(allJobs, length)
id <- rep(df$a, times = n)

#Turn allJobs into a vector
job <- unlist(allJobs)

#Retrieve position of each job
jobNum <- unlist(lapply(n, seq_len))

#Combine into a data frame
df2 <- data.frame(id = id, job = job, jobNum = jobNum)



回答2:


cSplit from my "splitstacksahpe" package is designed to handle this sort of data manipulation.

Here it is in action on this question:

df <- data.frame(a=c(1,2,3,4), 
               b=c("job1;job2", "job1a", "job4;job5;job6", "job9;job10;job11"))

# install.packages("splitstackshape")
library(splitstackshape)
cSplit(df, "b", ";", "long", makeEqual = FALSE)
#    a b_new
# 1: 1  job1
# 2: 1  job2
# 3: 2 job1a
# 4: 3  job4
# 5: 3  job5
# 6: 3  job6
# 7: 4  job9
# 8: 4 job10
# 9: 4 job11

You can also use strsplit within "dplyr", and then follow up with unnest from "tidyr", like this:

library(dplyr)
library(tidyr)
df %>% 
  mutate(b = strsplit(as.character(b), ";", fixed = TRUE)) %>% 
  unnest(b)
#   a     b
# 1 1  job1
# 2 1  job2
# 3 2 job1a
# 4 3  job4
# 5 3  job5
# 6 3  job6
# 7 4  job9
# 8 4 job10
# 9 4 job11


来源:https://stackoverflow.com/questions/4724938/r-split-unbalanced-list-in-data-frame-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!