I'm trying to get my Terms Documents Matrix which I transformed into a matrix profileM
, into a json file. My data looks like:
|AAZ | AA2 | AAR
--------|----------|---
are | 0 | 0 | 1
aze | 1 | 0 | 0
bar | 0 | 1 | 0
bor | 1 | 0 | 0
car | 0 | 1 | 0
dar | 0 | 0 | 1
Which is:
profileM = matrix( c(0,1,0,1,0,0, 0,0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1), nrow=6, ncol=3)
colnames(profileM) <- c("AAZ", "AA2", "AAR")
rownames(profileM) <- c("are", "aze", "bar", "bor", "car","dar")
I want the json file, which retains cells where the value is 1 (or above), to look like this :
{
"id": AAZ: {
"text": {
"aze", "bor"
}
},
"id": AA2: {
"text": {
"bar", "car"
}
},
"id": AAR: {
"text": {
"are", "dar"
}
}
}
I wrote this code:
for(col in 1:ncol(profileM)) {
x <- list(id = colnames(profileM)[col])
x <- append(x, x$id )
for(row in 1:nrow(profileM)) {
if (profileM[row, col] > 0){
x$text <- rownames(profileM)[row]
x <- append(x, x$text )
}
}
}
json <- jsonlite::toJSON(x)
json
and having this(which is wrong):
{"id":["AAR"],"2":["AAR"],"text":["dar"],"4":["are"],"5":["dar"]}
Could someone help to have a working code, specialy with apply
or sapply
? Thank you!