![](/img/trans.png)
[英]R. Data.table. How to diff columns with the same names for two different data.table?
[英]Operations on the columns with the same names in two data set in R
我有兩個數據集,如下所示:
df1 <- data.frame(a =c(1), b=c(4), c=c(1))
df2 <- data.frame (b =c(4), c=c(1), a=c(4))
我希望對具有相同名稱的列進行操作:例如,對於列a
,我想執行此操作(a(在df1中)-a(在df2中))/ a(在df1中)
那是(1-4) /1 = -3
所以我的理想輸出是:
a b c
-3 0 0
我將嘗試按以下方式編寫函數,但不確定如何進行。 任何提示都非常感謝。
my_func <- function(x,y) {
for (i in names(x))
if ((i %in% names(y))) {
df3 [i,] <- (x[i,] - y[i,]) / x[i,]
}
}
更新
理想情況下,如果我可以考慮缺少的列,那就太好了。 例如,如果df2中缺少列,則希望為0
,如果df2中缺少列,則輸出可以是“無值”之類的值
從@Headpoint答案獲得幫助,您可以直接執行此操作(無需循環)
df1 <- data.frame(a =c(1), b=c(4), c=c(1))
df1 <- df1[, order(names(df1))]
df2 <- data.frame (b =c(4), c=c(1), a=c(4))
df2 <- df2[, order(names(df2))]
all_col_names <- unique(colnames(df1), colnames(df2))
df1[, all_col_names] - df2[, all_col_names]
a b c
1 -3 0 0
這是你所追求的嗎?
res <- NULL
for (str in colnames(df1))
res <- c(res, (df1[str] - df2[str]) / df1[str] )
res
#$a
#[1] -3
#$b
#[1] 0
#$c
#[1] 0
如果您希望將其設為數字
out <- as.numeric(res)
names(out) <- names(res)
out
# a b c
#-3 0 0
如果列不匹配...
col_nam1 <- colnames(df1)
col_nam2 <- colnames(df2)
all_col_names <- unique(c(col_nam1, col_nam2))
res <- NULL
for (str in all_col_names)
if ((str %in% col_nam1) && (str %in%col_nam2))
res <- c(res, (df1[str] - df2[str]) / df1[str])
從@Hardik gupta啟發而來,沒有循環:
common_names <- sort(intersect(col_nam2, col_nam1))
(df1[, common_names] - df2[, common_names]) / df1[, common_names]
如果df1
具有df2
沒有的列,則df2
df1 <- data.frame(a =c(1), b=c(4), c=c(1), f = 4)
df2 <- data.frame (b =c(4), c=c(1), a=c(4), g = 5)
col_nam1 <- colnames(df1)
col_nam2 <- colnames(df2)
common_names <- intersect(col_nam2, col_nam1)
col_names <- sort(unique(col_nam1, common_names))
res <- numeric(length(col_names))
names(res) <- col_names
res[common_names] <- (df1[, common_names] - df2[, common_names]) /
df1[, common_names]
out <- as.numeric(res)
names(out) <- names(res)
out
a b c f
-3 0 0 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.