HI,
You can also use ifelse:
dat1<-read.table(text="
10/20/30
40/20
60/10/10/5
80/10
",sep="",header=FALSE,stringsAsFactors=FALSE)
dat2<-ifelse(nchar(gsub("[^/]","",dat1$V1))==1,gsub("(.*)/(.*)","\\1 0 0
\\2",dat1$V1),ifelse(nchar(gsub("[^/]","",dat1$V1))==2,gsub("(.*)/(.*)/(.*)","\\1
\\2 0 \\3",dat1$V1),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 <[email protected]>
To: R help <[email protected]>
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]]
______________________________________________
[email protected] 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.
______________________________________________
[email protected] 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.