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!
To convert List to Data Frame in R, call as. data. frame() function and pass the list as argument to it.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With