Search code examples
rfixed-width

Convert data saved in a comma delimited format to a fixed width format without package


I have a data file saved in a comma delimited format. However, it should be converted to a string format with a fixed width. I know that there is a package, gdata, out there. However, due to some technical limitation, I can't install the package. Without the package, the only approach I know is to use sprintf by specifying the format. However, I do have more than 100 variables. So, it is very tedious to write the format for every single variable. Could anyone help me to resolve this issue? Any help will be appreciated.

An Example is as below.

x<-data.frame(matrix(c("N",27,"P",3,"C","A","A","B","C","A","B","B","D","C"),nrow=1))

The width of the first 4 variables are 2,3,2,2 and the following variables are just 1. The outcome I want to have should look like

N 27 P 3 CAABCABBDC

Solution

  • Too bad you can't use gdata. you can paste the cols together after the fact

    x<-data.frame(matrix(c("N",27,"P",3,"C","A","A","B","C","A","B","B","D","C"),nrow=1))
    
    cols <-5:ncol(x) 
    x$newccol <- apply( x[ ,cols] , 1 , paste , collapse = "" )
    x[ ,cols ] <- NULL