Search code examples
rcat

Using cat function to write on csv file


I need to add new rows to a CSV using cat function. Would you guys help me, please? I am limited knowledge in R.

here's the file "name1.csv", I am asked to add my name and student ID to the first couple rows.

homework1 <- data.frame (homework1,Total)
homework1 <- data.frame (homework1, Commission)
# Create output file name using name1. All your output will go to this file.
sink("name1.csv")
# send the output to the csv file you just created
write.csv(homework1, file = "name1.csv")
# delete first column of the csv file
# Use cat function to write your name (First Last). This will be Row 1 of csv file. 
cat(file = "name1.csv", "Ibra", "\n", sep = ",", append=TRUE, row.names(F))

Solution

  • If you want to know how to use a function, you can call the help function on it:

    help(cat)
    

    Usage

    cat(... , file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)

    Arguments ...

    And it goes on.

    Cat will write to the sink by default. So if you want your name in the file to appear first. Start with catting your name:

    sink("name1.csv")
    cat("Ibra Lastname\n")  # sink is set, so file is not needed
    write.csv(homework1)
    

    Note that this will make the csv-file invalid; the first line will be a single string and the rest of the lines will have comma separated values of whatever the shape of homework1 is. This homework makes very little sense to me.