从多个数据框中选择第一行并绑定 [英] Select first row from multiple dataframe and bind

查看:58
本文介绍了从多个数据框中选择第一行并绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个数据框,它们已合并到一个列表中

I have three data frames which I have combined in a list

d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6))
d2 <- data.frame(y1 = c(3, 2, 1), y2 = c(6, 5, 4))
d3 <- data.frame(y1 = c(5, 7, 8),y2 = c(6, 4, 2))
my.list <- list(d1, d2,d3)

我想提取列表中每个元素的第一行,将它们按行绑定并另存为csv文件.

I want to extract the first row of each element in the list, bind them row wise and save as csv file.

例如,在上面的示例中,我想从d1d2d3

For example, in above example, I want to extract first row from d1, d2 and d3

row1.d1 <- c(1,4)
row1.d2 <- c(3,6)
row1.d3 <- c(5,6)

并将它们绑定在一起

dat <- rbind(row1.d1,row1.d2,row1.d3)
dat     

row1.d1    1    4
row1.d2    3    6
row1.d3    5    6

并对所有行重复一次.

如果有向量列表,我找到了一种方法,

I found a way to do this if I have a list of vectors,

 A=list()
 A[[1]]=c(1,2)
 A[[2]]=c(3,4)
 A[[3]]=c(5,6)

 sapply(A,'[[',1)

但是对于数据框,我不确定该如何处理.

But for dataframes, I am not sure how to go about it.

推荐答案

以下是tidyverse/FP解决方案.我添加了iddf来分别保留有关行号和源的信息.

A tidyverse/FP solution is below. I added id and df to retain information about the row number and source, respectively.

# your data
d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6))
d2 <- data.frame(y1 = c(3, 2, 1), y2 = c(6, 5, 4))
d3 <- data.frame(y1 = c(5, 7, 8),y2 = c(6, 4, 2))
my.list <- list(d1, d2,d3)


# tidyverse/ FP solution
library(dplyr)
library(purrr)
library(readr)

map_df(.x = seq(1:3),
       .f = function(x) bind_rows(my.list[x]) %>%
           mutate(id = row_number(),
                  df = x)) %>%
  arrange(id) %>%
  #select(-id, -df) %>% # uncomment if you want to lose row num and source
  write_csv(path = 'yourfile.csv')

这篇关于从多个数据框中选择第一行并绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆