# 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)


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
example(data.table)                   # run the examples section of ?

• it does not like transpose. also, the result needs to be a data frame. – Ray Tayek Jun 18 '18 at 9:51
• Oops, I missed one function - you still need the as.data.frame() function on the output of colMeans(). I edited the third line of my example to show it:  wc_2 <- transpose(as.data.frame(wc_2)). Also added it to the chain of the piped version. – n1k31t4 Jun 18 '18 at 9:55
• t seems to work instead of transpose. – Ray Tayek Jun 18 '18 at 10:22
• @RayTayek - I don't think you even need the matrix function. This returns the expected dataframe for me: data.frame(t(colMeans(worldcup['col1']))) – n1k31t4 Jun 18 '18 at 10:31
• yes, it seems to give the same result with out the call to matrix() – Ray Tayek Jun 18 '18 at 11:07