1) Read each file and convert it from JSON format into the desired form. Finally combine each one using rbind
.
# create test data
cat('{"Q0":1, "Q1":2, "Q2":3, "Q3":4, "Q15":5}\n', file = "file1.csv")
cat('{"Q0":11, "Q1":12, "Q2":13, "Q3":14, "Q15":15}\n', file = "file2.csv")
Files <- c("file1.csv", "file2.csv")
library(rjson)
m <- do.call("rbind", lapply(Files, function(f) {
x <- fromJSON(file = f)
cbind(Item = names(x), responses = unname(unlist(x)), file = f)
}))
giving this character matrix:
> m
Item responses file
[1,] "Q0" "1" "file1.csv"
[2,] "Q1" "2" "file1.csv"
[3,] "Q2" "3" "file1.csv"
[4,] "Q3" "4" "file1.csv"
[5,] "Q15" "5" "file1.csv"
[6,] "Q0" "11" "file2.csv"
[7,] "Q1" "12" "file2.csv"
[8,] "Q2" "13" "file2.csv"
[9,] "Q3" "14" "file2.csv"
[10,] "Q15" "15" "file2.csv"
2) If what you meant was that your starting point is not the files themselves but a data frame DF
with file
and responses
columns then:
# form input data frame -- this is the two columns shown in the question
DF <- data.frame(file = Files, responses = sapply(Files, readLines))
dd <- do.call("rbind", by(DF, DF$file, function(d) {
f <- as.character(d$file)
x <- fromJSON(json_str = as.character(d$responses))
data.frame(Item = names(x), responses = unname(unlist(x)), file = f,
stringsAsFactors = FALSE)
}))
rownames(dd) <- NULL
giving this data frame:
> dd
Item responses file
1 Q0 1 file1.csv
2 Q1 2 file1.csv
3 Q2 3 file1.csv
4 Q3 4 file1.csv
5 Q15 5 file1.csv
6 Q0 11 file2.csv
7 Q1 12 file2.csv
8 Q2 13 file2.csv
9 Q3 14 file2.csv
10 Q15 15 file2.csv