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

Massimo Bressan m@@@|mo@bre@@@n @end|ng |rom @rp@@veneto@|t
Tue Jun 12 17:07:27 CEST 2018

thank you for your reply 

well, you are resorting to a supposed order of i which is not necessary the case, and in fact is not in mine... 

consider this example, please 

d<-data.frame(i=c(8,12,3), s=c('97,918,19','103,1205', '418'), stringsAsFactors = FALSE) 

Da: "Bert Gunter" <bgunter.4567 using gmail.com> 
A: "Massimo Bressan" <massimo.bressan using arpa.veneto.it> 
Cc: "r-help" <R-help using r-project.org> 
Inviato: Martedì, 12 giugno 2018 16:42:18 
Oggetto: Re: [R] extract and re-arrange components of data frame 

You mean like this? 

> s.new <-with(d, as.numeric(unlist(strsplit(s,",")))) 

> s.new <- cut(s.new,breaks = c(0,100,110,200),lab = d$i) 

> s.new 
[1] 1 1 1 2 2 3 
Levels: 1 2 3 

(Obviously, this could be a one-liner) 

See ?cut 


Bert Gunter 

"The trouble with having an open mind is that people keep coming along and sticking things into it." 
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip ) 

On Tue, Jun 12, 2018 at 6:32 AM, Massimo Bressan < massimo.bressan using arpa.veneto.it > wrote: 

# 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) 

#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)) 

#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 

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

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

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

#any help for improving it? 
#a novice 

[[alternative HTML version deleted]] 

R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see 
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html 
and provide commented, minimal, self-contained, reproducible code. 

	[[alternative HTML version deleted]]

More information about the R-help mailing list