如何将 Named num [1:4] 转换为 R 中的数据框?

数据挖掘 r 在家工作
2022-03-11 06:15:19

r 的新手,从 coursera 学习R编程环境。其中一项任务是从数据框中选择一些列并找到方法。

下面的代码似乎得到了正确的答案,但答案应该是一个数据框。

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

如何将其转换为数据框?我试过了:wc_2<-as.data.frame(wc_2)但这让它变得明智。我看不到任何方法来传递行和列或在我假设是数据框构造函数中进行转置。

也许这可以作为管道的一部分来完成?

谢谢

编辑:我让它工作:

means <- worldcup %>% 
  select(Time, Passes, Tackles, Saves) %>%
    colMeans()
wc_2<-data.frame(t(matrix(means)))
colnames(wc_2)<-names(means)
1个回答

我首选的转置 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 ?