Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first row from multiple dataframe and bind

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.

like image 552
89_Simple Avatar asked Oct 16 '25 20:10

89_Simple


1 Answers

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
like image 192
jazzurro Avatar answered Oct 18 '25 10:10

jazzurro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!