Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change a named vector to a data frame retaining the names?

I have following data structure after executing a function:

      A       B       C        D        E       
      92.08   90.68   54.09    92.87    97.40    

      F       G       H        I        J       ...       
      24.52   67.24   15.63    22.33    45.10   ...  

As a final result, I want to have the data in a simple data frame, with letters as rows and values in a column. Following worked, though I'm curious whether this is the most elegant way(?):

output <- data.frame(output)
output <- data.frame(rownames(output), rowSums(output))
colnames(output) <- c("Category", "Value")
output
output %>% arrange(desc(output))

If you have an idea to make it better, feel free to correct me. dplyr solutions appreciated.

Thanks!

like image 866
Christopher Avatar asked Nov 26 '17 10:11

Christopher


People also ask

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

To convert List to Data Frame in R, call as. data. frame() function and pass the list as argument to it.

What is the difference between a vector and a data frame?

A vector can be defined as the sequence of data with the same datatype. In R, a vector can be created using c() function. R vectors are used to hold multiple data values of the same datatype and are similar to arrays in C language. Data frame is a 2 dimensional table structure which is used to hold the values.


1 Answers

As said by @Axeman in the comments, you have a named vector. The easiest way to transform that into a dataframe is by using the stack-function from base R.

Some example data:

output <- setNames(c(92.08,90.68,54.09,92.87,97.40), LETTERS[1:5])

which looks like:

> output
    A     B     C     D     E 
92.08 90.68 54.09 92.87 97.40

Transform into a dataframe with:

df <- stack(output)

which gives:

> df
  values ind
1  92.08   A
2  90.68   B
3  54.09   C
4  92.87   D
5  97.40   E

To get the columnnames and column order as specified in the question:

df <- setNames(stack(output)[2:1], c('Category','Value'))

which gives:

  Category Value
1        A 92.08
2        B 90.68
3        C 54.09
4        D 92.87
5        E 97.40
like image 71
Jaap Avatar answered Sep 28 '22 14:09

Jaap