How do i convert a Named num [1:4] to a data frame in R?

newbie to r, taking The R Programming Environment from coursera. one of the assignments is to select some columns from a data frame and find the means.

the code below seems to get the correct answer, but the answer should be a data frame.

wc_2 - worldcup %% 
  select(Time, Passes, Tackles, Saves) %%
    colMeans()

How do i convert this to a data frame? i tried: wc_2-as.data.frame(wc_2) but that gets it column wise. i do not see any way to pass the rows and columns or do a transpose in what i assume is a data frame constructor.

perhaps this can be done as part of the pipe?

thanks

edit: i got it to work:

means - worldcup %% 
  select(Time, Passes, Tackles, Saves) %%
    colMeans()
wc_2-data.frame(t(matrix(means)))
colnames(wc_2)-names(means)

Topic homework r

Category Data Science


My preferred way to transpose a data.frame (or data.table) is to use the transpose function found in the data.table package.

It means you might have to install it: install.packages("data.table"). This give you a function that will do what you want. Here is a demo how to use it:

library(data.table)    # makes the transpose function available

col_names <- colnames(worldcup)      # keep track of original column names
wc_2 <- colMeans(worldcup)           # compute the means
wc_2 <- transpose(as.data.frame(wc_2))              # this gives you generic column names
colnames(wc_2) <- col_names          # reapply the column names

Or combining it with your example (not fully tested):

library(magrittr)    # to import the pipe operator: %>%

wc_2 <- worldcup %>% 
  select(Time, Passes, Tackles, Saves) %>%
    colMeans() %>% as.data.frame() %>% transpose()       # you might need to put a dot (`.`) in the empty brackets to pass the argument before the pipe operator

then maybe add the names you would like:

colnames(wc_2) <- col_names

If you like the sound of the package, I recommend going through the mini intro, built in to the package:

install.packages("data.table")        # install it
library(data.table)                   # load it
example(data.table)                   # run the examples section of ?

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.