Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append group row into dataframe

I have this df1:

A B C
1 2 3
5 7 9

where A B C are columns names.

I have another df2 with one column:

A
1
2
3
4

I would like to append df2 for each column of df1, creating this final dataframe:

A B C 
1 2 3
5 7 9
1 1 1
2 2 2
3 3 3
4 4 4

is it possible to do it?

like image 893
giupardeb Avatar asked Sep 04 '17 20:09

giupardeb


3 Answers

data.frame(sapply(df1, c, unlist(df2)), row.names = NULL)
#  A B C
#1 1 2 3
#2 5 7 9
#3 1 1 1
#4 2 2 2
#5 3 3 3
#6 4 4 4

DATA

df1 = structure(list(A = c(1L, 5L), B = c(2L, 7L), C = c(3L, 9L)), .Names = c("A", 
"B", "C"), class = "data.frame", row.names = c(NA, -2L))

df2 = structure(list(A = 1:4), .Names = "A", class = "data.frame", row.names = c(NA, 
-4L))
like image 159
d.b Avatar answered Oct 16 '22 16:10

d.b


We can replicate df2 for the number of columns of df1, unname it, then rbind it.

rbind(df1, unname(rep(df2, ncol(df1))))
#   A B C
# 1 1 2 3
# 2 5 7 9
# 3 1 1 1
# 4 2 2 2
# 5 3 3 3
# 6 4 4 4

Data:

df1 <- structure(list(A = c(1L, 5L), B = c(2L, 7L), C = c(3L, 9L)), .Names = c("A", 
"B", "C"), class = "data.frame", row.names = c(NA, -2L))
df2 <- structure(list(A = 1:4), .Names = "A", row.names = c(NA, -4L), class = "data.frame")
like image 10
Rich Scriven Avatar answered Oct 16 '22 17:10

Rich Scriven


We can use base R methods

rbind(df1, setNames(as.data.frame(do.call(cbind, rep(list(df2$A), 3))), names(df1)))
#  A B C
#1 1 2 3
#2 5 7 9
#3 1 1 1
#4 2 2 2
#5 3 3 3
#6 4 4 4

data

df1 <- structure(list(A = c(1L, 5L), B = c(2L, 7L), C = c(3L, 9L)), .Names = c("A", 
"B", "C"), class = "data.frame", row.names = c(NA, -2L))

df2 <- structure(list(A = 1:4), .Names = "A", class = "data.frame",
row.names = c(NA, -4L))
like image 7
akrun Avatar answered Oct 16 '22 18:10

akrun