Adrian
Adrian

Reputation: 9803

subsetting data.frame without column names

test <- read.table(header = TRUE, text = "
MEMORY1 MEMORY2 MEMORY3 MEMORY4 MEMORY5 MEMORY6 MEMORY7 MEMORY8
7.5     5.      5.      2.      7.5     2.      2.      5.
6.      7.5     3.5     1.5     3.5     5.      1.5     7.5
6.      3.      3.      3.      3.      7.5     3.      7.5
3.5     3.5     3.5     3.5     3.5     7.5     3.5     7.5
5.      5.      5.      1.      5.      5.      5.      5.
5.      5.      2.      2.      7.      5.      2.      8.
")

I have a data.frame, and I would like to subset just the first row. If I do test[1, ], the result is

> test[1, ]
  MEMORY1 MEMORY2 MEMORY3 MEMORY4 MEMORY5 MEMORY6 MEMORY7 MEMORY8
1     7.5       5       5       2     7.5       2       2       5

How do I subset the data.frame so that I get just a vector of the numbers without the column names?

Upvotes: 15

Views: 35426

Answers (2)

akrun
akrun

Reputation: 887881

You can use unlist with option use.names=FALSE to return only vector without names.

unlist(test[1,], use.names=FALSE)
#[1] 7.5 5.0 5.0 2.0 7.5 2.0 2.0 5.0

test[1,] is still a data.frame with 8 columns. A data.frame can be regarded as a list having the same length for its list elements (or columns). So we can use unlist. This also works when you are creating a vector from more than one row.

unlist(test[1:2,], use.names=FALSE)

Or as @Frank suggested, if we are subsetting multiple rows by keeping the dimensions, we set the names to NULL and convert to matrix.

 as.matrix(setNames(test[1:2,],NULL))

Upvotes: 10

user295691
user295691

Reputation: 7248

What you want is a numeric vector instead of a data.frame. For this, you can just use as.numeric to do the conversion

> as.numeric(df[1,])
[1] 7.5 5.0 5.0 2.0 7.5 2.0 2.0 5.0

Upvotes: 12

Related Questions