本文介绍了从多个数据框中选择第一行并绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将三个数据框合并到一个列表中
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.
例如,在上面的例子中,我想从 d1
、d2
和 d3
中提取第一行
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
并对所有行重复此操作.
and repeat it for all rows.
如果我有一个向量列表,我找到了一种方法,
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 解决方案如下.我添加了 id
和 df
以分别保留有关行号和来源的信息.
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')
这篇关于从多个数据框中选择第一行并绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!