如何将整个数据帧附加到 R 中的 CSV?
R编程语言中的数据框是以表格的形式排列的行和列的表格排列。 CSV 文件还包含存储在一起以形成堆叠在一起的行的数据。可以从 CSV 文件读取和写入内容。 Base R 包含多种方法来处理这些文件。 write.csv() 方法覆盖文件的全部内容。因此,它会导致原始 CSV 内容被删除。
修改是对文件的内容进行的。如果 row.names 设置为 TRUE,则数据可能会变得不明确,因为行号会附加到数据的开头,并且所有行都将一个位置向右移动。 sep 参数对于区分行是必要的,否则会产生不正确的结果。
Syntax:
write.table(df, csv- file , append = TRUE, sep = “,”, col.names = FALSE, row.names = FALSE)
Parameters :
df – The data frame to be appended
csv-file – The file name to append to
append – Indicator of whether to merge to existing contents or not
col.names – Indicator of whether to append column headings to the csv.
默认情况下,行号附加在行的开头,从整数值 1 开始。
使用中的数据集:
例子:
R
# specifying the path of csv file
path <- "gfg.csv"
# read contents of file
content1 <- read.csv(path)
print ("Original content")
# displaying original content
print (content1)
# creating data frame to append
data_frame <- data.frame(ID = c(8:9),
Name = c("K","L"),
Post= c("IT","Writer"),
Age = c(18,27))
# writing contents of the file
content <- write.table(data_frame , path, append = T ,
col.names = FALSE,sep = ",",
row.names = F)
# contents of the csv file
content2 <- read.csv(path)
print ("Modified content")
# displaying modified content
print (content2)
R
path <- "gfg.csv"
content1 <- read.csv(path)
print ("Original content")
print (content1)
# creating data frame to append
data_frame <- data.frame(ID = c(8:9),Name = c("K","L"),
Post= c("IT","Writer"),Age = c(18,27))
# writing contents of the file
content <- write.table(data_frame , path, append = T ,
col.names = TRUE,sep = ",", row.names = F)
# contents of the csv file
content2 <- read.csv(path)
print ("Modified content")
print (content2)
输出
[1] “Original content”
ID Name Post Age
1 5 H CA 67
2 6 K SDE 39
3 7 Z Admin 28
[1] “Modified content”
ID Name Post Age
1 5 H CA 67
2 6 K SDE 39
3 7 Z Admin 28
4 8 K IT 18
5 9 L Writer 27
如果 col.names 参数设置为 TRUE,则列标题将作为一行附加在数据之前。这会导致列标题显示两次,结果中会返回一个额外的行。数据框的列名可能与 CSV 文件的行标题相同,也可能不同。
例子:
电阻
path <- "gfg.csv"
content1 <- read.csv(path)
print ("Original content")
print (content1)
# creating data frame to append
data_frame <- data.frame(ID = c(8:9),Name = c("K","L"),
Post= c("IT","Writer"),Age = c(18,27))
# writing contents of the file
content <- write.table(data_frame , path, append = T ,
col.names = TRUE,sep = ",", row.names = F)
# contents of the csv file
content2 <- read.csv(path)
print ("Modified content")
print (content2)
输出
[1] “Original content”
ID Name Post Age
1 5 H CA 67
2 6 K SDE 39
3 7 Z Admin 28
[1] “Modified content”
ID Name Post Age
1 5 H CA 67
2 6 K SDE 39
3 7 Z Admin 28
4 ID Name Post Age
5 8 K IT 18
6 9 L Writer 27