匹配和相减:一列到多列

问题描述 投票:0回答:3

我有两个数据表,一个有两列,另一个有多个列。

表1

Samples Val
a        2
b       58 
c        4
d      100

表2

Samples  A1    A2    A3
a       100    67     3
c        54    89   120
d        23    64    46
f         6    99    35 

现在我在 R 中遇到了一个大问题:

当样本匹配时,我想从 table1 的值 (Val) 中减去 table2 的值。 最终减去的值应替换 table2 中的值(或新表中的行和列名称应与 table2 相同)。 价值观 < 0 should be replace by 0

决赛桌应该是这样的:

决赛桌

Samples  A1    A2    A3
a        98    65     1
c        50    85   116
d         0     0     0
f         6    99    35

有人可以帮我吗?

r dplyr replace matching subtraction
3个回答
0
投票

您可以使用

dplyr
来检查
across
列,使用如下所示的
ifelse
语句:

library(dplyr)

table2 %>%
  left_join(., table1, by = "Samples") %>%
  mutate(across(A1:A3, ~ ifelse(!is.na(Val), .x - Val, .x))) %>%
  mutate(across(A1:A3, ~ ifelse(.x < 0 , 0, .x))) %>%
  select(-Val)
#>   Samples A1 A2  A3
#> 1       a 98 65   1
#> 2       c 50 85 116
#> 3       d  0  0   0
#> 4       f  6 99  35

创建于 2023-08-16,使用 reprex v2.0.2


使用数据:

table1 = read.table(text = "Samples Val
a        2
b       58 
c        4
d      100", header = TRUE)
 
table2 = read.table(text = "Samples  A1    A2    A3
a       100    67     3
c        54    89   120
d        23    64    46
f         6    99    35 ", header = TRUE) 

0
投票

或者在

base r

merged_data <- merge(table2, table1, by = "Samples", all= TRUE)

merged_data$Val <- ifelse(!is.na(merged_data$Val),merged_data$Val,0)
merged_data[, -1] <- merged_data[, -1] - merged_data$Val
merged_data[, 5] <- NULL

merged_data <- merged_data[rowSums(!is.na(merged_data[, -1]))>0,]

merged_data[rowSums(merged_data[,-1]<0)==3,-1] <- 0 

merged_data

创建于 2023-08-16,使用 reprex v2.0.2

  Samples A1 A2  A3
1       a 98 65   1
3       c 50 85 116
4       d  0  0   0
5       f  6 99  35

0
投票

创建一个与样本名称匹配的向量,然后减去:

x <- table1$Val[ match(table2$Samples, table1$Samples)] 
# if sample doesn't match, then zero, nothing to subtract
x <- ifelse(is.na(x), 0, x)
x
# [1]   2   4 100   0

table2[, -1] <- table2[, -1] - x

#if negative then assign zero
table2[, -1][ table2[, -1] < 0 ] <- 0

table2
#   Samples A1 A2  A3
# 1       a 98 65   1
# 2       c 50 85 116
# 3       d  0  0   0
# 4       f  6 99  35
© www.soinside.com 2019 - 2024. All rights reserved.