Question

I need to generate .dat files with some requirements, to be analysed by a specific software. The format of the .dat file should: have certain fixed width in the ID column, and show the item response values all together with no separators. Exactly like this:

(ID)   (i1i2i3...values) 
1      1234
2      1234
3      1234
4      1234
...
2365   1234

I could get the fixed width characters by IDfixed <- sprintf("%04d", ID), and include the variable in this code:

  for(i in 0:5) {
  for (j in 1:5) {
    filename <- paste("Factor",j, "_", "Facet",i+1, "_", "ID", ".dat", sep="")
    write.table(cbind(IDfixed, data[,c(2*i+1,2*i+2),j]), filename, col.names=F, row.names=F)
  }
}

The output shoulnd't have these "" characters -it must have the same format as the former table. A sample of the result:

     [,1]   [,2] [,3]
[1,] "0001" "2"  "1" 
[2,] "0002" "2"  "3" 
[3,] "0003" "5"  "5" 
[4,] "0004" "3"  "3" 
[5,] "0005" "3"  "5"

Thanks for your time!

Était-ce utile?

La solution

Try this:

# sample data
ID <- c(1, 11, 111, 1111)

# convert ID to character, pad with leading zeros to a fixed width of 4
IDfixed <- sprintf("%04d", ID)

IDfixed
# [1] "0001" "0011" "0111" "1111"

edit The default behavior of write.table is that "any character or factor columns will be surrounded by double quotes" (quote = TRUE). To avoid the "" around elements in 'ID' to be written to the file, use quote = FALSE.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top