[R] splits with 0s in middle columns

Rui Barradas ruipbarradas at sapo.pt
Fri Aug 31 23:17:32 CEST 2012


Hello,

It means you should update your version of R. paste0 was introduced with 
R 2.15.0 as is the shorter equivalent of

paste(..., sep = "")

I'm sending you a small correction just in case some of the elements in 
A only have 1 element.

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)
         if(m > 1){
             tmp[n] <- x[m]
             tmp[seq_len(m - 1)] <- x[seq_len(m - 1)]
         }else tmp[1] <- x
         tmp
     }

     res <- do.call(rbind, lapply(s, f))
     colnames(res) <- paste(xname, seq_along(s), sep = "")
     data.frame(res)
}

Rui Barradas

Em 31-08-2012 21:58, Sapana Lohani escreveu:
> Hi Rui,
>
> I am getting some error message in the code you sent. It says "Error in fun(A) : could not find function "paste0"
>
> I am a new in R so could not fix it. Can you help me fix that ?
>
> Thanks
>
>
>
>
> ________________________________
>   From: Rui Barradas <ruipbarradas at sapo.pt>
> To: Sapana Lohani <lohani.sapana at ymail.com>
> Cc: r-help <r-help at r-project.org>
> Sent: Friday, August 31, 2012 12:35 PM
> Subject: Re: [R] splits with 0s in middle columns
>   
> 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