[R] splits with 0s in middle columns
Rui Barradas
ruipbarradas at sapo.pt
Fri Aug 31 21:35:48 CEST 2012
Hello,
Try the following.
A <- c(
"10/20/30",
"40/20",
"60/10/10/5",
"80/10")
fun <- function(X){
xname <- deparse(substitute(X))
s <- strsplit(X, "/")
n <- max(sapply(s, length))
tmp <- numeric(n)
f <- function(x){
x <- as.numeric(x)
m <- length(x)
tmp[n] <- x[m]
tmp[seq_len(m - 1)] <- x[seq_len(m - 1)]
tmp
}
res <- do.call(rbind, lapply(s, f))
colnames(res) <- paste0(xname, 1:ncol(res))
data.frame(res)
}
fun(A)
Hope this helps,
Rui Barradas
Em 31-08-2012 17:10, Sapana Lohani escreveu:
> 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