kevinykuo
kevinykuo

Reputation: 4762

Extract rows from data frame as list of vectors

For example, I have the data

a <- c("a", "b", "c")
b <- c("x", "y", "z")
df <- data.frame(a = a, b = b)

I want to do something to df so my result is

list(c("a", "x"), c("b", "y"), c("c", "z"))

I want the solution to be vectorized, and I'm having trouble utilizing the right *apply functions...

Upvotes: 0

Views: 433

Answers (2)

jlhoward
jlhoward

Reputation: 59355

Here's another way.

as.data.frame(t(df),stringsAsFactors=FALSE,row.names=NA)
#   V1 V2 V3
# 1  a  b  c
# 2  x  y  z

This produces a data frame, which is in fact a list of vectors. If you must have a "true" list, you could use this:

as.list(as.data.frame(t(df),stringsAsFactors=FALSE,row.names=NA))
# $V1
# [1] "a" "x"
#
# $V2
# [1] "b" "y"
#
# $V3
# [1] "c" "z"

Upvotes: 2

MrFlick
MrFlick

Reputation: 206243

If you want to split up a data.frame by rows, try

 split(df, seq.int(nrow(df)))

Upvotes: 3

Related Questions