-1

I am beginner in R I have binary csv file, for example:

   a;b;c;d
 A;0;0;1;1
 B;1;1;1;0
 C;1;1;0;1
 D;0;0;0;1

I am read in R

data <- read.csv2("/home/beka/data.csv",sep = ";",header = TRUE)

How i can to write a new file like: For ex:

A;a;0
A;b;0
A;c;1
A;d;0
B;a;1
B;b;1

Thanks

Dossanov
  • 121
  • 1
  • 1
  • 9
  • `?write.csv2` : it has a `sep` parameter which can be used to tell it to use `;` instead of `,` and it also has a `col.names` parameter which can be set to `FALSE` to stop it from including the header. – hrbrmstr Apr 30 '18 at 09:35
  • Look into reshape2's "melt" function https://cran.r-project.org/web/packages/reshape2/reshape2.pdf – d0d0 Apr 30 '18 at 09:36

2 Answers2

0

You can use base R's stack to reshape your data.

df.out <- setNames(
    data.frame(rep(rownames(df), each = ncol(df)), stack(df)[c(2, 1)]),
    c("row", "col", "val"))
df.out;
#   row col val
#1    A   a   0
#2    A   a   1
#3    A   a   1
#4    A   a   0
#5    B   b   0
#6    B   b   1
#7    B   b   1
#8    B   b   0
#9    C   c   1
#10   C   c   1
#11   C   c   0
#12   C   c   0
#13   D   d   1
#14   D   d   0
#15   D   d   1
#16   D   d   1

Save as CSV file with write.csv(df.out, row.names = FALSE).


Sample data

df <- read.table(text =
    "   a;b;c;d
A;0;0;1;1
B;1;1;1;0
C;1;1;0;1
D;0;0;0;1", sep = ";", header = T)
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
0

We can use melt after converting to matrix

library(reshape2)
melt(as.matrix(df))
akrun
  • 874,273
  • 37
  • 540
  • 662