我首选的转置 a data.frame(or data.table) 的方法是使用data.table 包transpose中的函数。
这意味着您可能必须安装它:install.packages("data.table"). 这给了你一个可以做你想做的事情的功能。这是一个演示如何使用它:
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
或将其与您的示例结合(未经过全面测试):
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
然后也许添加您想要的名称:
colnames(wc_2) <- col_names
如果您喜欢包装的声音,我建议您阅读包装中内置的迷你介绍:
install.packages("data.table") # install it
library(data.table) # load it
example(data.table) # run the examples section of ?