使用 R 将行附加到 CSV
在本文中,我们将看到如何使用 R 编程语言将行附加到 CSV 文件。
默认情况下, write.csv()函数覆盖整个文件内容。为了将数据附加到 CSV 文件,请改用write.table()方法并设置参数append = TRUE 。 write.table 方法在将 .csv 文件转换为文件或连接的数据框时打印其所需的参数 x。
Syntax:
write.table(x, file = “”, append = FALSE, quote = TRUE, sep = ” “, row.names = TRUE, col.names = TRUE)
Parameters:
- x : The row data in the data frame object
- file : The file to append row to
- sep : The field separator string, that is within each row of x values are separated by this separator.
如果文件为空,则在同一目录中创建时将内容写入 .csv 文件。以下代码说明了 write.table() 方法对空 .csv 文件的适用性。
例子
R
# defining the data for the csv file
# data is organised into 4 columns
data = data.frame(ID = 1:4, Name = c("A","B","C","D"),
Post=c("Peon","SDE","Manager","SDE"),
Age = c(23,39,28,39))
# write data to a sample.csv file
write.table(data, file = "sample.csv")
R
# defining a row
row <- data.frame('1', 'A', 'Manager', '24')
# sample csv name
csv_fname = "sample.csv"
# writing row in the csv file
write.table(row, file = csv_fname, sep = ",",
append = TRUE, quote = FALSE,
col.names = FALSE, row.names = FALSE)
输出
以下代码段显示了如何将一行附加到已经由几行组成的 CSV 文件。对指定的 CSV 文件进行更改,并且在每次操作时,一行计数都会增加。
例子:
电阻
# defining a row
row <- data.frame('1', 'A', 'Manager', '24')
# sample csv name
csv_fname = "sample.csv"
# writing row in the csv file
write.table(row, file = csv_fname, sep = ",",
append = TRUE, quote = FALSE,
col.names = FALSE, row.names = FALSE)
输出