[R] extract and re-arrange components of data frame

Massimo Bressan m@@@imo@bre@@@n @ending from @rp@@veneto@it
Tue Jun 12 15:32:57 CEST 2018


# considering this data.frame as a reproducible example 
d<-data.frame(i=c(1,2,3), s=c('97,98,99','103,105', '118'), stringsAsFactors = FALSE) 
d 

#I need to get this final result 
r<-data.frame(i=c(1,1,1,2,2,3), s=c(97, 98, 99, 103, 105, 118)) 
r 

#this is my attempt 

#number of components for each element (3) of the list 
#returned by strsplit 
n<-unlist(lapply(strsplit(d$s,','), length)) 

#extract components of all elements of the list 
s<-cbind(unlist(strsplit(d$s,','))) 

#replicate each element of i 
#by the number of components of each element of the list 
i<-rep(d$i, n) 
i 

#compose final result 
r_final<-data.frame(i,s, stringsAsFactors = FALSE) 
r_final 

#I'm not much satisfied by the approach, it seems to me a bit clumsy... 

#any help for improving it? 
#thanks 
#a novice 



	[[alternative HTML version deleted]]



More information about the R-help mailing list