R语言 如何编辑CSV文件

R语言 如何编辑CSV文件

在这篇文章中,我们将学习如何在R编程语言中编辑CSV文件。

什么是CSV文件

逗号分隔值(CSV) 文件是一个简单的纯文本文件,包含一个由分隔符分隔的数据列表。顾名思义,在这些文件中,存储的信息是由逗号分隔的。

R有内置的CSV解析器功能,这是读取、写入、编辑和处理CSV文件数据的最可靠和最简单的方法之一。

创建一个CSV文件

要创建一个CSV文件,我们需要在一个文本文件中保存由逗号分隔的数据,并以.csv为扩展名保存该文件。另一种创建CSV文件的方法是使用google sheets或excel。让我们使用下面的数据创建一个CSV文件,并将其保存为shop.csv。

Product,Size,Color,Price
Shirt,Medium,Blue,1039
T-Shirt,small,Green,1899
Jeans,large,Black,1299
Shirt,Medium,White,1999
R

CSV文件

如何在R语言中编辑CSV文件

CSV文件

读取CSV文件

注意,CSV文件应该存在于当前工作目录中,否则我们必须给出该文件的完整位置。现在我们要导入我们在R中创建的CSV文件,打印该文件并执行一些操作,如使用 nrow()ncol() 方法提取行和列的数量,使用 min()max() 方法提取列中的最小和最大值。

# Read shop.csv file
data <- read.csv("shop.csv")
# Print csv file
print(data)
# Printing total number of columns
cat("Total Columns: ", ncol(data))
# Print total number of rows
cat("Total Rows:", nrow(data))
# Store minimum value of Price column
min_price <- min(dataPrice)
# Store maximum value of Price column
max_price <- max(dataPrice)
cat("Min. price :",min_price)
cat("Max. price :",max_price)
R

输出:

  Product   Size Color Price
1   Shirt Medium  Blue  1039
2 T-Shirt  small Green  1899
3   Jeans  large Black  1299
4   Shirt Medium White  1999
Total Columns:  4
Total Rows: 4
Min. price : 1039
Max. price : 1999
R

在R中编辑CSV文件

在CSV文件中删除和添加行

要编辑CSV文件,我们要做的是从上一步创建的CSV文件中删除一行,在删除一行后,使用 rbind()函数 为CSV文件中要添加的行创建一个新的数据框,添加新的行。

# Read shop.csv file
data <- read.csv("shop.csv")
# Print csv file
print(data)
# Printing total number of columns
cat("Total Columns: ", ncol(data))
# Print total number of rows
cat("Total Rows:", nrow(data))
# Store minimum value of Price column
min_price <- min(dataPrice)
# Store maximum value of Price column
max_price <- max(dataPrice)
cat("Min. price :",min_price)
cat("Max. price :",max_price)
 
# Delete 4th row from data
data <- data[-c(4),]
# Assigning column values
Product <- c("Jacket")
Size <- c("Medium")
Color <- c("Cyan")
Price <- c(5999)
 
# Creating new row
new_row <- data.frame(Product,Size,
                      Color,Price)
print(new_row)
# Append new row in CSV file
data <- rbind(data,new_row)
print(data)
R

输出

[1] "File before edit"
  Product   Size Color Price
1   Shirt Medium  Blue  1039
2 T-Shirt  small Green  1899
3   Jeans  large Black  1299
4   Shirt Medium White  1999

[1] "File after edit"
  Product   Size Color Price
1   Shirt Medium  Blue  1039
2 T-Shirt  small Green  1899
3   Jeans  large Black  1299
4  Jacket Medium  Cyan  5999
R

在CSV文件中添加和删除列

我们可以用下面的方法在CSV文件中删除和增加列,让我们看看代码。

# Adding column to dataframe
data$quantity <- c(10,20,10,5)
 
# Writing to csv file
write.csv(data,"path to csv file",
          row.names=FALSE)
R

解释: 在上面的代码中,首先我们在数据框架中添加一列,然后将其写入CSV文件。

如何在R语言中编辑CSV文件

添加一个数量列

为了从CSV文件中删除列,我们使用了与上面相同的方法,但为了删除列,我们使用”$”操作符在该列中存储 NULL

# Deleting Size column
data$Size <- NULL
 
# Writing to csv file
write.csv(data,"path to csv file",
          row.names=FALSE)
R

输出

如何在R语言中编辑CSV文件

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册