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

Bert Gunter bgunter@4567 @end|ng |rom gm@||@com
Tue Jun 12 16:42:18 CEST 2018


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

Cheers,
Bert





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)
> 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]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> 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