简体   繁体   English

如何从R中的.csv文件中读取列向量

[英]How to read in column vectors from a .csv file in R

So I have data being processed in Python that I'm outputting as a .csv file. 所以我在Python中处理数据,我输出的是.csv文件。 I would like R to be able to read the .csv file in such a way that it turns it into a dataframe in which some of the columns are actually vectors. 我希望R能够以这样一种方式读取.csv文件,它将它变成一个数据帧,其中一些列实际上是向量。

Is this even possible and how would I format a .csv so that this could happen? 这甚至是可能的,我将如何格式化.csv以便这可能发生? Thanks! 谢谢!

First, vectors are simply a sequence of data elements. 首先, 向量只是一系列数据元素。 And data frames are lists of equal length vectors. 数据帧是等长矢量的列表。

Hence, you can easily reference each column of a data frame as a vector. 因此,您可以轻松地将数据框的每一列作为向量引用。

df <- read.csv('C:\\Path\\To\\DataFile.csv')

v1 <- df[[1]]  # by column number
v2 <- df[["col1"]]  # by column name
v3 <- df$col1  # by column name

You can just read the csv in r and it will be a dataframe by default: 您可以在r中读取csv,默认情况下它将是一个数据帧:

data<-read.csv("nameOfCSVFile.csv", header=T)

You can then slice the dataframe by column and obtain that column as a vector using the $ operator: data$header1 returns the first column of the dataframe as a vector. 然后,您可以按列对数据帧进行切片,并使用$运算符将该列作为向量获取: data$header1将数据帧的第一列作为向量返回。

Just make sure that your .csv file is in the order you want ie 只需确保您的.csv文件符合您的要求,即

header1,header2,etc.
     1,2,etc.
     4,5, etc.
     etc..

Actually, a dataframe is a collection of vectors. 实际上,数据帧是矢量的集合。 If you want to have the data in form of a vector, you simple have to use the subsetting functions: 如果你想以向量的形式获得数据,你必须使用子集函数:

df <- data.frame(matrix(rnorm(10), nrow=5))

 df$X1
## [1]  1.05376208  0.05020266  1.79204302 -1.73712344 -1.29208706
 is.vector(df$X1)
## [1] TRUE

So by subsetting, here you get a vector of the data frame column X1 . 因此,通过子集化,您可以获得数据帧列X1的向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM