0

I want to write a R function to insert many 0 vectors into a existed data.frame. Here is the example:

Data.frame 1
    A   B   C   D
1   1   3   4   5
2   4   5   6   7
3   4   5   6   2
4   4   55  2   3

Data.frame 2
    A   B   E   X
11  5   1   5   5
22  44  55  9   6
33  12  4   2   4
44  9   7   4   2

Based on the union of two colnames (that is A,B,C,D,E, X), I want to update the two data frames like:

Data.frame 1 (new)

    A   B   C   D   E   X
1   1   3   4   5   0   0
2   4   5   6   7   0   0
3   4   5   6   2   0   0
4   4   55  2   3   0   0

Data.frame 2 (new)

    A   B   C   D   E   X
11  5   1   0   0   5   5
22  44  55  0   0   9   6
33  12  4   0   0   2   4
44  9   7   0   0   4   2

Thanks in advance.

4

1 回答 1

3

选项 1(感谢@Jilber 的编辑)

我假设列的顺序无关紧要 -

df2part <- subset(df2,select = setdiff(colnames(df2),colnames(df1)))*0
df1f <- cbind(df1,df2part)
df1part <- subset(df1,select = setdiff(colnames(df1),colnames(df2)))*0
df2f <- cbind(df2,df1part)

如果顺序真的很重要,那么只需重新排序列

df2f <- df2f[, sort(names(df2f))]

输出

> df1f
  A  B C D E X
1 1  3 4 5 0 0
2 4  5 6 7 0 0
3 4  5 6 2 0 0
4 4 55 2 3 0 0
> df2f
    A  B C D E X
11  5  1 0 0 5 5
22 44 55 0 0 9 6
33 12  4 0 0 2 4
44  9  7 0 0 4 2

选项 2 -

library(data.table)
df1 <- data.table(df1)
df2 <- data.table(df2)

df1names <- colnames(df1)
df2names <- colnames(df2)
df1[,setdiff(df2names,df1names) := 0]
df2[,setdiff(df1names,df2names) := 0]
于 2013-10-24T23:23:00.573 回答