Reputation: 2232
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!
Upvotes: 11
Views: 4277
Reputation: 83215
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
Upvotes: 20