[R] splits with 0s in middle columns

arun smartpink111 at yahoo.com
Sat Sep 1 03:24:58 CEST 2012


Hi,
Try this:
dat1<-read.table(text="
10/20/30
40/20
60/10/10/5
80/10
",sep="",header=FALSE,stringsAsFactors=FALSE)
dat2<-gsub("(.*)/(.*)","\\1 0 0 \\2", gsub("(.*)/(.*)/(.*)","\\1 \\2 0 \\3", gsub("(.*)/(.*)/(.*)/(.*)","\\1 \\2 \\3 \\4",dat1$V1)))
dat3<-data.frame(do.call(rbind,strsplit(dat2, " ")))
 colnames(dat3)<-paste0("A",1:4)
 dat3
#  A1 A2 A3 A4
#1 10 20  0 30
#2 40  0  0 20
#3 60 10 10  5
#4 80  0  0 10
A.K.




----- Original Message -----
From: Sapana Lohani <lohani.sapana at ymail.com>
To: R help <r-help at r-project.org>
Cc: 
Sent: Friday, August 31, 2012 12:10 PM
Subject: [R] splits with 0s in middle columns

Hi, 

A column of my df looks like

A
10/20/30

40/20
60/10/10/5
80/10

I want to split it such that the last column has the last composition and if there are not enough the middle columns get the 0s. That way my df would look like

A1 A2 A3 A4
10 20 0 30
40 0 0 20
60 10 10 5
80 0 0 10

How can I do that ??

    [[alternative HTML version deleted]]

______________________________________________
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.




More information about the R-help mailing list