我有两个数据表,一个有两列,另一个有多个列。
表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 88 65 1
c 50 85 116
d 0 0 0
f 6 99 35
有人可以帮我吗?
您可以使用
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)