create a csv file in r

In R, you can create a CSV file using the write.csv() function. Before that, you need to have the data that you want to write in the CSV file in the form of a data frame.

Here is an example code to create a CSV file named "data.csv" using the write.csv() function:

main.r
# Create a data frame
df <- data.frame(name = c("John", "Alice", "Bob"),
                 age = c(25, 30, 35),
                 salary = c(50000, 60000, 70000))

# Write the data frame to a CSV file
write.csv(df, file = "data.csv", row.names = FALSE)
251 chars
8 lines

In the above code, we first created a data frame named "df" with three columns and three rows. We then used the write.csv() function to write this data frame to a file named "data.csv" in the current working directory.

The row.names = FALSE argument specifies that we do not want to write the row names of the data frame to the CSV file. If you want to include the row names, set this argument to TRUE.

Note that if the file already exists, write.csv() function will overwrite it. If you want to append to an existing file, use write.table() function with argument append = TRUE.

gistlibby LogSnag