Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a data frame that is a subset of two data frames

Tags:

r

I am stumped again.

I have two data frames

dataframe1

     a     b    c
[1]  21   12   22
[2]  11    9    6
[3]   4    6    7

and

dataframe2

      f    g   h
[1]  21   12   22
[2]  11    9    6
[3]   4    6    7

I want to take the first column of dataframe1 and make three new dataframes with the second column being each of the three f,g and h

Obviously I could just do a subset over and over

subset1 <- cbind(dataframe1[,1]dataframe2[,1])
subset2 <- cbind(dataframe1[,1]dataframe2[,2])

but my dataframes will have variable numbers of columns and are very long row numberwise. So I am looking for a little more something general. My data frames will always be the same length.

The closest I have come to getting anything was with apply and cbind but I got either a set of three rows that were a and f, a and g, a and h each combined as single numeric vector or I get a single data frame with four columns, a,f,g,h.

Help is deeply appreciated.

like image 902
Natalie Bjorklund Avatar asked Nov 20 '25 04:11

Natalie Bjorklund


1 Answers

You can use lapply it iterate over the columns of dataframe2 like so:

lapply(dataframe2, function(x) as.data.frame(cbind(dataframe1[,1], x)))

This will result in a list object where each entry corresponds to a column of dataframe2. For example:

$f
  V1  x
1 21 21
2 11 11
3  4  4

$g
  V1  x
1 21 12
2 11  9
3  4  6

$h
  V1  x
1 21 22
2 11  6
3  4  7
like image 135
Chase Avatar answered Nov 22 '25 19:11

Chase



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!