我有一个体积测量的大脑部分(视叶,嗅叶,听觉皮质等),所有的部分将加起来总的大脑体积。如这里的示例数据帧所示。
a b c d e total
1 2 3 4 5 15
2 3 4 5 6 20
4 6 7 8 9 34
7 8 10 10 15 50
如果我从总体积中减去一个分量,我想找出大脑体积的差异。所以我想知道如何在R中进行,而不必为每个大脑部分创建一个新的列。
For example: (total - a = 14, total - b =13, and so on for other components).
total-a total-b total-c total-d total-e
14 13 12 11 10
18 17 16 15 14
30 28 27 26 25
43 42 40 40 35
发布于 2019-04-10 05:26:45
你可以做到
dat[, "total"] - dat[1:5]
# a b c d e
#1 14 13 12 11 10
#2 18 17 16 15 14
#3 30 28 27 26 25
#4 43 42 40 40 35
发布于 2019-04-10 05:29:01
如果您还需要列名,那么一种可能的tidyverse
可能是:
df %>%
gather(var, val, -total) %>%
mutate(var = paste0("total-", var),
val = total - val) %>%
spread(var, val)
total total-a total-b total-c total-d total-e
1 15 14 13 12 11 10
2 20 18 17 16 15 14
3 34 30 28 27 26 25
4 50 43 42 40 40 35
如果您不关心列名,那么只需使用dplyr
就可以做到:
df %>%
mutate_at(vars(-matches("(total)")), list(~ total - .))
a b c d e total
1 14 13 12 11 10 15
2 18 17 16 15 14 20
3 30 28 27 26 25 34
4 43 42 40 40 35 50
或者不使用列名,只使用base R
df[, grepl("total", names(df))] - df[, !grepl("total", names(df))]
a b c d e
1 14 13 12 11 10
2 18 17 16 15 14
3 30 28 27 26 25
4 43 42 40 40 35
https://stackoverflow.com/questions/55601529
复制相似问题