Select first row from multiple dataframe and bind

≡放荡痞女 提交于 2019-12-11 01:10:57

问题


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)

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

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)

and bind them together

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.


回答1:


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')



回答2:


Another way would be the following. You go through each data frame in my.list and get the first row with lapply(). Then you bind the result.

do.call(rbind, (lapply(my.list, function(x) x[1,])))

#  y1 y2
#1  1  4
#2  3  6
#3  5  6



回答3:


We need to use , after the 1

t(sapply(my.list, `[`, 1, ))


来源:https://stackoverflow.com/questions/48150776/select-first-row-from-multiple-dataframe-and-bind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!