Reputation: 485
I have a data frame called dataf
dataf<-data.frame(replicate(10,sample(0:1,10,rep=TRUE)))
and I would like to extract each row of this data frame as a character string like with this function :
result=data.frame(matrix(NA, ncol=1, nrow=10))
i=0
for(i in 0:9)
{
result[i+1,]=toString(dataf[i+1,])
}
but result is not as expected :
1, 0, 0, 0, 1, 0, 0, 1, 1, 0
0, 0, 0, 1, 1, 1, 1, 0, 1, 1
1, 1, 0, 0, 0, 0, 0, 0, 1, 0
I would like this:
"1","0","0","0","1","0","0","1","1","0"
"0","0","0","1","1","1","1","0","1","1"
"1","1","0","0","0","0","0","0","1","0"
I already tried with dQuote
, with \"R\"
, with collapse
, with sep
... but I don't get what I need.
Upvotes: 2
Views: 586
Reputation: 44614
This is another option, similar to @Phil's in approach, but gives the same output as @JayBlack.
apply(dataf, 1, function(.) paste(dQuote(.), collapse=','))
This returns the following vector of strings.
[1] "\"0\",\"0\",\"1\",\"0\",\"1\",\"1\",\"0\",\"0\",\"1\",\"1\""
[2] "\"1\",\"0\",\"1\",\"1\",\"1\",\"0\",\"0\",\"0\",\"1\",\"0\""
[3] "\"1\",\"1\",\"0\",\"1\",\"0\",\"0\",\"1\",\"1\",\"1\",\"1\""
.....
Upvotes: 2
Reputation: 28461
[Edit]
Here's a way:
d <- apply(dataf, 1, toString)
splitup <- lapply(d, function(x) paste('\"', unlist(strsplit(x, ',')), ',\"', sep=''))
data.frame(do.call(rbind, splitup))
X1 X2 X3 X4 X5 X6 X7 X8 X9
1 "1," " 0," " 0," " 1," " 1," " 0," " 1," " 0," " 1,"
2 "1," " 0," " 1," " 1," " 0," " 1," " 0," " 0," " 0,"
3 "0," " 0," " 1," " 0," " 1," " 0," " 1," " 0," " 0,"
4 "0," " 1," " 1," " 1," " 0," " 0," " 1," " 1," " 1,"
5 "1," " 0," " 1," " 0," " 0," " 1," " 0," " 1," " 1,"
6 "1," " 0," " 1," " 1," " 0," " 0," " 0," " 1," " 0,"
7 "1," " 0," " 1," " 0," " 0," " 1," " 1," " 1," " 1,"
8 "0," " 1," " 0," " 1," " 0," " 1," " 0," " 1," " 1,"
9 "1," " 1," " 1," " 0," " 0," " 1," " 0," " 1," " 0,"
10 "0," " 0," " 0," " 0," " 0," " 1," " 0," " 0," " 1,"
Upvotes: 1
Reputation: 34586
Try: capture.output(write.table(lapply(dataf, as.character), row.names=F, col.names=F, sep=","))
[1] "\"0\",\"0\",\"0\",\"0\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\""
[2] "\"1\",\"0\",\"1\",\"0\",\"0\",\"0\",\"1\",\"0\",\"1\",\"1\""
[3] "\"0\",\"1\",\"0\",\"0\",\"1\",\"1\",\"0\",\"0\",\"1\",\"1\""
...
Edited in response to Matthew's comment below
Upvotes: 3
Reputation: 4444
EDIT: Not the output you specified but may be useful to others?
apply(dataf, 1, paste0, collapse = "")
Yields:
[1] "0000000101" "0100100111" "1110101001" "1001010101" "1011111100" "1010000111"
[7] "0110001110" "1111000011" "1001101000" "0010011010"
Is that the output you hoped for?
Upvotes: 0