write to a file in r

To write to a file in R, you can use the write() function to write text to a file, or the write.csv() function to write a data frame to a csv file.

Here's an example of writing to a text file:

# Create a character vector to write to file
my_text <- c("This", "is", "some", "text")

# Open a file for writing
file_conn <- file("my_text.txt", "w")

# Write to the file
write(my_text, file_conn)

# Close the file connection
close(file_conn)
246 chars
12 lines

And here's an example of writing a data frame to a CSV file:

# Create a data frame
my_data <- data.frame(
  name = c("John", "Jane", "Bob"),
  age = c(28, 33, 45)
)

# Write the data frame to a CSV file
write.csv(my_data, file = "my_data.csv", row.names = FALSE)
202 chars
9 lines

In both cases, the resulting file will be written to the current working directory unless a full file path is provided.

related categories

gistlibby LogSnag