Phil Goetz Phil Goetz - 24 days ago 6
R Question

R: Why doesn't as.vector give a vector when given the output of read.table?

On the output of read.table, as.vector produces an m x 1 matrix rather a length m vector:

# data.txt contains one integer per line and nothing else
dataframe = read.table("data.txt", encoding='UTF-8', header=F)
v = as.vector(dataframe)
is.vector(v)
[1] FALSE
length(v)
[1] 1
dim(v)
[1] 19783 1

Answer

To summerise the above data types:

  • Data frame: A tabular object where each column can be a different type. A data frame is really a list.
  • Matrix: A tabular object where all values must have the same type.
  • Vector: A one dimensional object; all values must have the same type.

Hence it doesn't (in general) make sense to convert from a data frame to a vector.

In your example, you can either

unlist(dataframe)

or convert to a matrix, then use as.vector

as.vector(data.matrix(dataframe))