Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert named vector to dataframe

I have this named vector:

x <-  1:5

names(x) <- c('0 15', '1 15', '2 15', '0 16', '1 16')

What is the best way to convert x to this dataframe:

xDF <- data.frame(V1 = c(0, 1, 2, 0, 1), V2 = c(15, 15, 15, 16, 16), V3 = 1:5)
like image 838
luciano Avatar asked Jun 10 '13 09:06

luciano


People also ask

What does Tibble :: Enframe () do?

enframe() converts named atomic vectors or lists to one- or two-column data frames. For a list, the result will be a nested tibble with a column of type list . For unnamed vectors, the natural sequence is used as name column.

How do I convert a list to a DataFrame in R?

Convert List to DataFrame using data. data. frame() is used to create a DataFrame in R that takes a list, vector, array, etc as arguments, Hence, we can pass a created list to the data. frame() function to convert list to DataFrame. It will store the elements in a single row in the DataFrame.


Video Answer


2 Answers

Here's a very direct approach:

cbind(read.table(text = names(x)), x)
     V1 V2 x
0 15  0 15 1
1 15  1 15 2
2 15  2 15 3
0 16  0 16 4
1 16  1 16 5

In this case, read.table will automatically take care of splitting your names(x) component (by default, by space, but other characters could be specified if necessary).

You can also set the name for x directly in cbind:

cbind(read.table(text = names(x)), V3 = x)

A more direct approach would be to use cSplit from my "splitstackshape" package, like this:

library(splitstackshape)
cSplit(stack(x), "ind", " ")
like image 104
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 04 '22 01:10

A5C1D2H2I1M1N2O1R2T1


I'd do something like this:

res = data.frame(cbind(do.call('rbind', strsplit(names(x), " ")), x))
res
     V1 V2 x
0 15  0 15 1
1 15  1 15 2
2 15  2 15 3
0 16  0 16 4
1 16  1 16 5

Do mind that the data types are not correct yet, the first two columns are factor's.

like image 39
Paul Hiemstra Avatar answered Oct 04 '22 00:10

Paul Hiemstra