Praveen Chougale
Praveen Chougale

Reputation: 383

How to add row and column to a dataframe of different length?

I have two dataframes of different length:

Headers <- data.frame(x = paste0("x", 1:4), y = 1:4)
Dataset <- data.frame(H = c(20, 10, 11, 8, 10), W = c(30, 20, 30, 10, 6)) 

Headers
   x y
1 x1 1
2 x2 2
3 x3 3
4 x4 4

Dataset
   H  W
1 20 30
2 10 20
3 11 30
4  8 10
5 10  6

I need to convert column 'x' from 'Headers' to header, and column 'y' to corresponding values, and then bind to 'Dataset':

H   W  x1  x2  x3  x4
20  30  1   2   3   4
10  20  1   2   3   4
11  30  1   2   3   4
 8  10  1   2   3   4
10   6  1   2  3    4

Here is the code which I tried:

 H <- t(Headers)
 Dataset <- cbind(H, Dataset)
 names(H)  <- NULL
 Dataset <- qpcR:::cbind.na(H, Dataset)

Any help will be appreciated.Thanks

Upvotes: 1

Views: 213

Answers (3)

Henrik
Henrik

Reputation: 67778

Transpose 'y' and repeat to the desired number of rows. Set column names to 'x'.

cbind(Dataset, `colnames<-`(t(Headers$y)[rep(1, nrow(Dataset)), ], Headers$x))

   H  W x1 x2 x3 x4
1 20 30  1  2  3  4
2 10 20  1  2  3  4
3 11 30  1  2  3  4
4  8 10  1  2  3  4
5 10  6  1  2  3  4

Upvotes: 1

CER
CER

Reputation: 889

You could also go with basic R

cbind(Dataset,data.frame(matrix(rep(Headers$y,each=nrow(Dataset)),nrow=nrow(Dataset))))

Upvotes: 0

arg0naut91
arg0naut91

Reputation: 14764

A data.table approach:

library(data.table)

cbind(Dataset, dcast(Headers, . ~ x, value.var = "y")[,-1])

Output:

   H  W x1 x2 x3 x4
1 20 30  1  2  3  4
2 10 20  1  2  3  4
3 11 30  1  2  3  4
4  8 10  1  2  3  4
5 10  6  1  2  3  4

A tidyverse approach:

library(tidyverse)

Headers %>%
  rownames_to_column %>%
  spread(x, y) %>%
  summarise_all(funs(first(na.omit(.)))) %>%
  cbind(Dataset, .) %>% select(-rowname)

Output:

   H  W x1 x2 x3 x4
1 20 30  1  2  3  4
2 10 20  1  2  3  4
3 11 30  1  2  3  4
4  8 10  1  2  3  4
5 10  6  1  2  3  4

Upvotes: 0

Related Questions