0

I have two data frames in R with different underlying data.

The first data frame has character data, while the second has numeric data. Each data frame is a different length.

Is there a way to combine these data frames of different lengths AND different data types into one data frame.

The goal is to create a 6x2 data frame with the data repeated.

Example:

a = c("1M", "2M") # 2x1 vector
b = c(0.75, 0.80, 0.85) # 3x1 vector

a = as_tibble(a)
b = as_tibble(b)

c1 = c("1M", "1M", "1M", "2M", "2M", "2M")
c2 = c(0.75, 0.80, 0.85, 0.75, 0.80, 0.85)

result_mat = cbind(c1, c2)
result_mat = as_tibble(result_mat) # 6x2 data frame

Aveshen Pillay
  • 431
  • 3
  • 13
  • is your expected correct. `as_tibble` instead of `as_tibbl` – akrun Apr 24 '23 at 17:01
  • Columns in data frames are atomic, meaning they entire column be of the same type. If you try to mix types there is a hierarchy for coercing them. You can see this happening in your `c1` and `c2` vectors. You mixed character and numeric, the result is a character vector. – LMc Apr 24 '23 at 17:01
  • 1
    It might be helpful to explain what you are trying to accomplish. It is likely there is a better way to go about what you need to do. Do the numeric values correspond to the character values in someway? – LMc Apr 24 '23 at 17:05
  • I made a mistake in the `result_mat` which I have corrected now. It should be the first vector repeated element wise in the first column where the repetitions is the length of the second vector. – Aveshen Pillay Apr 24 '23 at 17:08

1 Answers1

2

You can use rep to repeat your vectors using the arguments each and times:

data.frame(
  c1 = rep(a, each = length(b)),
  c2 = rep(b, times = length(a))
)

Alternatively, if you are working in the tidyverse you can use crossing:

tidyr::crossing(a, b)

Output

  c1   c2
1 1M 0.75
2 1M 0.80
3 1M 0.85
4 2M 0.75
5 2M 0.80
6 2M 0.85
LMc
  • 12,577
  • 3
  • 31
  • 43