write to a csv file in r

To write data to a CSV file in R, you can use the write_csv function from the readr package. Here's an example:

main.r
# example data frame
my_df <- data.frame(
  name = c("Alice", "Bob", "Charlie"),
  age = c(25, 30, 35),
  profession = c("doctor", "engineer", "teacher")
)

# write data to a CSV file
library(readr)
write_csv(my_df, "my_data.csv")
231 chars
11 lines

This code creates a data frame called my_df, which contains three columns (name, age, and profession). The write_csv function is then used to write the data frame to a CSV file called my_data.csv.

If you want to write data to an existing CSV file, you can use the write_csv2 function instead of write_csv. This function is identical to write_csv, but uses a semicolon (;) as the field separator instead of a comma.

main.r
# example data frame
my_df <- data.frame(
  name = c("Alice", "Bob", "Charlie"),
  age = c(25, 30, 35),
  profession = c("doctor", "engineer", "teacher")
)

# write data to an existing CSV file
library(readr)
write_csv2(my_df, "my_existing_data.csv")
251 chars
11 lines

In this code, the write_csv2 function is used to write the data frame to an existing CSV file called my_existing_data.csv. The original contents of the file will be overwritten.

gistlibby LogSnag