问题描述
这似乎相当简单,我只需要从R中的数据文件中读取奇数行,并创建一个新的数据帧.我该如何实现?
This seems fairly simple, I need to read only odd numbered rows from a data file in R and create a new data frame. How can I achieve this?
推荐答案
read.csv("filename.csv")[c(TRUE, FALSE), ]
工作方式:
函数read.csv
用于读取整个文件并返回包含所有行的数据帧.然后,[x, ]
用于从数据帧中提取某些行.如果c(TRUE, FALSE)
(2)的向量长度小于数据帧的行数,则将循环使用向量值,直到向量的长度与行数匹配为止.如果数据帧具有例如5行,则向量为c(TRUE, FALSE, TRUE, FALSE, TRUE)
.对应于TRUE
的所有行都将被选中.因此,这将选择具有奇数行号的行.
The function read.csv
is used to read the whole file and returns a data frame including all rows. Then, [x, ]
is used for extracting certain rows from the data frame. If the vector length of c(TRUE, FALSE)
(2) is below the number of rows of the data frame, the vector values will be recycled until the length of the vector matches the number of rows. If the data frame has, e.g., 5 rows, the vector is c(TRUE, FALSE, TRUE, FALSE, TRUE)
. All rows corresponding to TRUE
will be selected. Hence, this will select rows with odd row numbers.
顺便说一句:如果要选择偶数行号,则可以使用c(FALSE, TRUE)
.
By the way: If you want to select even row numbers, you can use c(FALSE, TRUE)
.
这篇关于从csv文件中读取奇数行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!