[R] binary conversion list to data.frame with plyr... AND NO LOOPS!
jim holtman
jholtman at gmail.com
Sat Jul 9 01:09:59 CEST 2011
try this:
> x <- c(36, 40, 10, 4)
> x.m <- matrix(as.integer(intToBits(x)), byrow = TRUE, ncol = 32)[, 1:20]
> x.m <- data.frame(x.m) # convert to data.frame
> x.m
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14 X15 X16 X17 X18 X19 X20
1 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
3 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
4 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
>
On Fri, Jul 8, 2011 at 6:39 PM, Justin Haynes <jtor14 at gmail.com> wrote:
> Happy weekend helpeRs!
>
> As usual, I'm stumped by R...
>
> My plan was to take an integer number, convert it to binary and wind
> up with a data.frame where each column is either 1 or 0 so I can see
> which bits are changing:
>
> bb<-function(i) ifelse(i, paste(bb(i %/% 2), i %% 2, sep=""), "")
> my.dat<-c(36,40,10,4)
> my.binary.dat<-bb(my.dat)
> my.list<-strsplit(my.binary.dat,'')
>
> max.len<-max(ldply(my.list,length))
> len<-length(my.list)
> my.df<-data.frame(two=rep(0,len),four=rep(0,len),eight=rep(0,len),sixteen=rep(0,len),thirtytwo=rep(0,len),sixtyfour=rep(0,len))
> for(i in 1:length(my.list)){
> for(j in 1:length(my.list[[i]])){
> my.df[i,max.len-length(my.list[[i]])+j]<-my.list[[i]][j]
> }
> }
>
> But this isn't exactly feasable on a million+ rows where some binary
> numbers are 20 digits... I know theres a way without loops I just
> know it!
>
> Ideally, I can do this to multiple columns of a data.frame and have
> them named accordingly (V1.two,V1.four... V2.two,V2.four, etc.)
>
>
> Thanks,
>
> Justin
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>
--
Jim Holtman
Data Munger Guru
What is the problem that you are trying to solve?
More information about the R-help
mailing list