Reputation: 59
I can't seem to find answer though I'm sure it's already been asked...but I wanted to extract and combine a subset of data.frame columns into a single list without use of any packages. For example:
DF <- data.frame(a = c(1,2,3), b = c(4,5,6), c = c(7,8,9))
test <- c(DF[,1], DF[,2], DF[,3]) # Gives what I want
test <- c(DF[,1:3]) # Doesn't give what I want
So desired output would be a single list of values 1:9. I'd want the subset to be dynamically assigned so I can't do it the way I typed it even though it is giving the output I'd like. The only other way I could think is to have a loop and incrementally add one column at a time e.g. test <- c(test, DF[,i])
Upvotes: 1
Views: 1107
Reputation: 887981
An option with flatten
from purrr
library(dplyr)
library(purrr)
DF %>%
flatten_dbl
#[1] 1 2 3 4 5 6 7 8 9
Upvotes: 1
Reputation: 14774
You can just unlist
:
unlist(DF)
# a1 a2 a3 b1 b2 b3 c1 c2 c3
# 1 2 3 4 5 6 7 8 9
And to get rid of names if needed:
unlist(DF, use.names = FALSE) # or also unname(unlist(DF))
# [1] 1 2 3 4 5 6 7 8 9
Upvotes: 1
Reputation: 102920
Maybe you can try c
within do.call
test <- do.call(c,DF)
such that
> test
a1 a2 a3 b1 b2 b3 c1 c2 c3
1 2 3 4 5 6 7 8 9
Upvotes: 1