How To Use Append Function

Hello everyone,

I have this code here, that will import a bunch of files in a loop, but I want the files to append, instead of replace. Can anyone help me with that?

i = length(filenames)
x = 1
while (x < i) {
  append(test, test = fromJSON(file = filenames[x]))
  x = x+1
}

filenames is the name of the files
and test is what I want the files to append to

That code probably looks weird, but that's because I was getting frustrated and just started randomly (and furiously) typing stuff.

Thanks

Is test a vector?

Depending on the type of vector you could use map_* functions from the purrr package.

output <- map_chr(filenames, ~fromJSON(file = .x))

If the output from fromJSON is not a character, then you could use one of the other variants. There is map_dbl for class double, map_int for integers, map_lgl for logicals, map_dfr for dataframes/tibbles that you want binded by rows (i.e. binded like bind_rows or rbind) and map_dfc for dataframes/tibbles you want binded by column (i.e. binded by bind_cols or cbind).

If you are not sure of the output, you could simply use map in place of map_chr and it will return a list instead of a vector.

1 Like

Do you mean you want to combine the contents of the files into another file, or the contents of all the files into a single character vector?

1 Like

I want to combine them all into one file.

Ex: Say one of my files has 13 rows. And the one after also has 13. After I finish running my code, I should have 26 rows. My data is data from a JSON file, and is a dataframe, if that helps.

Thanks

You can read each file into a data.frame, collect those data.frames in a list, and then bind them together row-wise:

library(jsonlite)
library(dplyr)

datasets <- lapply(filenames, fromJSON)
combined <- bind_rows(datasets)
writeLines(toJSON(combined), "combined.json")
1 Like