如何将excel内容转换为R中的DataFrame?
R 编程语言允许我们将数据读写到各种文件中,如 CSV、Excel、XML 等。在本文中,我们将讨论如何在 R 编程中将 excel 内容转换为 DataFrame。要读取 excel 文件本身,请使用 xlsx 中的read.xlsx()函数。
安装
该模块未内置于 R 中,但可以显式安装和导入。打开 R 控制台并输入下面给出的命令来安装 xlsx 包。
install.packages(“xlsx”)
read_xlsx() 可以通过以下方式使用:
Syntax: read.xlsx(“Excel File Path”, sheetName = “sheet name”, …)
Parameters: it is necessary to give the Excel file path and sheetName as argument in read.xlsx() function but many other parameters can be used by this function such as colNames, rowNames, skipEmptyRows, skipEmptyCols, rows, cols, etc. for doing some extra modifications. Here we used colIndex as parameter for getting only column that we want. here we give 1 as a value of colIndex parameter for getting first column of Excel file.
使用中的文件:ID Name Age 1225 John 19 1226 Jane 19 1227 Bill 65 1228 Elon 49
首先,我们使用library()函数导入xlsx包,然后将 Excel 文件的完整路径提供给excel_path命名变量。要创建数据框,请继续从文件中提取列,并在完成后将它们组合成一个数据框。
程序:
R
library(xlsx)
excel_path <- "excelContent.xlsx"
id <- read.xlsx(excel_path, sheetName = "ageData", colIndex = 1)
Name <- read.xlsx(excel_path, sheetName = "ageData", colIndex = 2)
Age <- read.xlsx(excel_path, sheetName = "ageData", colIndex = 3)
DataFrame <- data.frame(id, Name, Age)
输出: