我有下面的输入,我想减去两列,但我想总是从最高值中减去最低值。 因为我不希望结果为负值,有时最高值出现在第一列(PaternalOrgin)中,有时出现在第二列中(MaternalOrigin)。
输入:
df <- PaternalOrigin MaternalOrigin
16 20
3 6
11 0
1 3
1 4
3 11
,输出输出为:
df <- structure(list(PaternalOrigin = c(16, 3, 11, 1, 1, 3), MaternalOrigin = c(20, 6, 0, 3, 4, 11)), colnames = c("PaternalOrigin", "MaternalOrigin"), row.names= c(NA, -6L), class="data.frame")
因此,我的预期输出看起来像:
df2 <- PaternalOrigin MaternalOrigin Results
16 20 4
3 6 3
11 0 11
1 3 2
1 4 3
3 11 8
拜托,有人可以告诉我吗? 感谢。
答案 0 :(得分:0)
我们可以使用transform(df, Results = abs(PaternalOrigin - MaternalOrigin))
# PaternalOrigin MaternalOrigin Results
#1 16 20 4
#2 3 6 3
#3 11 0 11
#4 1 3 2
#5 1 4 3
#6 3 11 8
df$Results <- with(df, abs(PaternalOrigin - MaternalOrigin))
或者我们可以将其分配给“结果”
data.table
或使用library(data.table)
setDT(df)[, Results := abs(PaternalOrigin - MaternalOrigin)]
dplyr
或library(dplyr)
df %>%
mutate(Results = abs(PaternalOrigin - MaternalOrigin))
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-xxxxxxxxxx",
enable_page_level_ads: true
});
</script>