R - 对数据列成对应用计算 frame/data table
R - applying calculation pairwise on columns of data frame/data table
假设我有具有相同列名的数据框
DF1 = data.frame(a = c(0,1), b = c(2,3), c = c(4,5))
DF2 = data.frame(a = c(6,7), c = c(8,9))
并想对它们应用一些基本计算,例如添加每一列。
由于我也想让目标数据框显示丢失的数据,所以我在DF2中追加了这样一列,所以我有
> DF2
a c b
1 6 8 NA
2 7 9 NA
我现在在这里尝试的是创建数据框
for(i in names(DF2)){
DF3 = data.frame(i = DF1[i] + DF2[i])
}
(然后将其绑定在一起)但这显然行不通,因为列的顺序被混淆了。
所以,
当列的顺序不相同而不重新排序时,进行这种成对计算的最佳方法是什么?
我也尝试过(因为这是我认为可以解决的问题)
for(i in names(DF2)){
DF3 = data.frame(i = DF1$i + DF2$i)
}
但这不起作用,因为 DF1$i
对所有 i
都是 NULL
。
结论:我要数据框
>DF3
a b c
1 6+0 NA 4+8
2 1+7 NA 5+9
如有任何帮助,我们将不胜感激。
这可能有帮助 -
#Get column names from DF1 and DF2
all_cols <- union(names(DF1), names(DF2))
#Fill missing columns with NA in both the dataframe
DF1[setdiff(all_cols, names(DF1))] <- NA
DF2[setdiff(all_cols, names(DF2))] <- NA
#add the two dataframes arranging the columns
DF1[all_cols] + DF2[all_cols]
# a b c
#1 6 NA 12
#2 8 NA 14
我们可以使用bind_rows
library(dplyr)
library(data.table)
bind_rows(DF1, DF2, .id = 'grp') %>%
group_by(grp = rowid(grp)) %>%
summarise(across(everything(), sum), .groups = 'drop') %>%
select(-grp)
-输出
# A tibble: 2 x 3
a b c
<dbl> <dbl> <dbl>
1 6 NA 12
2 8 NA 14
另一个基本 R 选项使用 aggregate
+ stack
+ reshae
aggregate(
. ~ rid,
transform(
reshape(
transform(rbind(
stack(DF1),
stack(DF2)
),
rid = ave(seq_along(ind), ind, FUN = seq_along)
),
direction = "wide",
idvar = "rid",
timevar = "ind"
),
rid = 1:nrow(DF1)
),
sum,
na.action = "na.pass"
)[-1]
给予
values.a values.b values.c
1 6 NA 12
2 8 NA 14
假设我有具有相同列名的数据框
DF1 = data.frame(a = c(0,1), b = c(2,3), c = c(4,5))
DF2 = data.frame(a = c(6,7), c = c(8,9))
并想对它们应用一些基本计算,例如添加每一列。
由于我也想让目标数据框显示丢失的数据,所以我在DF2中追加了这样一列,所以我有
> DF2
a c b
1 6 8 NA
2 7 9 NA
我现在在这里尝试的是创建数据框
for(i in names(DF2)){
DF3 = data.frame(i = DF1[i] + DF2[i])
}
(然后将其绑定在一起)但这显然行不通,因为列的顺序被混淆了。
所以, 当列的顺序不相同而不重新排序时,进行这种成对计算的最佳方法是什么?
我也尝试过(因为这是我认为可以解决的问题)
for(i in names(DF2)){
DF3 = data.frame(i = DF1$i + DF2$i)
}
但这不起作用,因为 DF1$i
对所有 i
都是 NULL
。
结论:我要数据框
>DF3
a b c
1 6+0 NA 4+8
2 1+7 NA 5+9
如有任何帮助,我们将不胜感激。
这可能有帮助 -
#Get column names from DF1 and DF2
all_cols <- union(names(DF1), names(DF2))
#Fill missing columns with NA in both the dataframe
DF1[setdiff(all_cols, names(DF1))] <- NA
DF2[setdiff(all_cols, names(DF2))] <- NA
#add the two dataframes arranging the columns
DF1[all_cols] + DF2[all_cols]
# a b c
#1 6 NA 12
#2 8 NA 14
我们可以使用bind_rows
library(dplyr)
library(data.table)
bind_rows(DF1, DF2, .id = 'grp') %>%
group_by(grp = rowid(grp)) %>%
summarise(across(everything(), sum), .groups = 'drop') %>%
select(-grp)
-输出
# A tibble: 2 x 3
a b c
<dbl> <dbl> <dbl>
1 6 NA 12
2 8 NA 14
另一个基本 R 选项使用 aggregate
+ stack
+ reshae
aggregate(
. ~ rid,
transform(
reshape(
transform(rbind(
stack(DF1),
stack(DF2)
),
rid = ave(seq_along(ind), ind, FUN = seq_along)
),
direction = "wide",
idvar = "rid",
timevar = "ind"
),
rid = 1:nrow(DF1)
),
sum,
na.action = "na.pass"
)[-1]
给予
values.a values.b values.c
1 6 NA 12
2 8 NA 14