How to append group row into dataframe

2019-03-15 00:11发布

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?

9条回答
别忘想泡老子
2楼-- · 2019-03-15 00:59

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")
查看更多
爷的心禁止访问
3楼-- · 2019-03-15 00:59

Data:

df1 <- data.frame(A=c(1,5),
                  B=c(2,7),
                  C=c(3,9))
df2 <- data.frame(A=c(1,2,3,4))

Solution:

df2 <- matrix(rep(df2$A, ncol(df1)), ncol=ncol(df1))
colnames(df2) <- colnames(df1)
rbind(df1,df2)

Result:

  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
查看更多
爷、活的狠高调
4楼-- · 2019-03-15 01:03

I just love R, here is yet another Base R solution but with mapply:

data.frame(mapply(c, df1, df2))

Result:

  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

Note:

No need to deal with colnames like almost all the other solutions... The key to why this works is that "mapply calls FUN for the values of ... [each element] (re-cycled to the length of the longest...[element]" (See ?mapply). In other words, df2$A is recycled to however many columns df1 has.

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")
查看更多
登录 后发表回答