【问题标题】:transpose a columns to row in a list of dataframes and write it to a new dataframe in R将列转置为数据帧列表中的行并将其写入 R 中的新数据帧
【发布时间】:2021-01-31 01:45:46
【问题描述】:

我有一个数据框列表,需要转置数据框中的每一列并创建一个新的数据框。这是一个可重现的例子。所以我需要通过为列表中的每个数据框转置 4 列来创建 4 个大小为 500 行和 100 列的数据框。

  # simulate list of 500 dataframes where each dataframe has 100 rows and 4 columns

    mat<-as.matrix(diag(c(1,2,3,4)))

  dat<-list()
     for (i in 1:500){
   dat[[i]]<-as.data.frame(mvrnorm(100,rep(0,4),mat))
                     }

 # I need an output that would look something like this - transpose first column in each of the 500 
 dataframes and combine into a single dataframe. I am showing for 3 dataframes in a list.

 t(dat[[1]][,1])
 t(dat[[2]][,1])
 t(dat[[3]][,1])


dat.1<-rbind(t(dat[[1]][,1]),t(dat[[2]][,1]),t(dat[[3]][,1]))
 head(dat.1)

# Tried doing this function for transposing first column of each of the 500 dataframes in the list
 # but gives an error that "dim(X) must have positive length ".
    dat.1<-apply(dat,1,function(x){t(dat[[x]][,1])})

【问题讨论】:

    标签: r


    【解决方案1】:

    我认为这就是你想要的:

    do.call(rbind, lapply(dat, `[`, , 1L))
    

    【讨论】:

      【解决方案2】:

      你可以试试:

      result <- do.call(rbind,lapply(dat, `[[`, 1))
      

      【讨论】:

        【解决方案3】:

        tidyverse,我们可以使用

        library(dplyr)
        library(purrr)
        map_dfr(dat, `[`, 1)
        

        【讨论】:

          猜你喜欢
          • 2020-08-25
          • 2023-01-21
          • 2015-08-11
          • 2019-09-01
          • 2019-06-16
          • 2021-07-25
          • 2017-08-22
          • 1970-01-01
          相关资源
          最近更新 更多