R中的只读文件头
在本文中,我们将看到 R 编程语言中的文件头。
方法一:使用 read.table 方法
R 中的 read.table() 方法用于访问存储在 CSV 文件的组织结构中的内容。
Syntax: read.table(path, head = TRUE, nrows, sep = “;”)
Arguments:
- path: The complete directory path where the file is stored
- head: a logical value, indicator of whether the file contains the names of the variables as its first line or not.
- nrows: the maximum number of rows to read into the working directory
代码:
R
# creating a data frame
data_frame1 <- data.frame(col1 = c(6:8),
col2 = letters[1:3],
col3 = c(1,4,NA))
# speicfying data path
path <- "/Users/mallikagupta/Desktop/rcontent.csv"
# writing data to csv
write.csv2(data_frame1,
path,
row.names = FALSE)
# reading
read.table(path,
head = TRUE,
nrows = 1,
sep = ";")[- 1, ]
R
# creating a data frame
data_frame1 <- data.frame(col1 = c(6:8),
col2 = letters[1:3],
col3 = c(1,4,NA))
# speicfying data path
path <- "/Users/mallikagupta/Desktop/rcontent.csv"
# writing data to csv
write.csv2(data_frame1,
path,
row.names = FALSE)
# reading header
colnames(read.csv2(path))
输出
[1] col1 col2 col3
<0 rows> (or 0-length row.names)
方法二:使用 colnames 方法
R 中的 read.csv2() 方法用于将 CSV 文件从指定的路径参数读取到表格结构中。
Syntax: read.csv2(path)
Arguments :
path: The complete directory path where the file is stored
基础 R 中的 colnames() 方法用于收集分配给 CSV 文件的表格结构的列名。它将从文件中读取的表格结构作为参数。
Syntax: colnames(df)
Arguments :
df: The data frame to read the header of
代码:
电阻
# creating a data frame
data_frame1 <- data.frame(col1 = c(6:8),
col2 = letters[1:3],
col3 = c(1,4,NA))
# speicfying data path
path <- "/Users/mallikagupta/Desktop/rcontent.csv"
# writing data to csv
write.csv2(data_frame1,
path,
row.names = FALSE)
# reading header
colnames(read.csv2(path))
输出
[1] "col1" "col2" "col3"