r - 如何对这些数据进行排序以将特定列与 R 中的其他列相减

标签 r

这是我的数据的一小部分样本,请考虑我有超过 100 列

I   D   M   N   Score
12  23  11  12  22
11  11  11  11  33
11  11  10  11  44
12  11  12  11  66
11  11  11  12  50

我想从每列中减去分数以获得下表:

Score1  I   Score2  D   Score3  M   Score4  N
10  12  -1  23  12  11  10  12
22  11  22  11  0   11  22  11
33  11  33  11  1   10  33  11
54  12  55  11  -1  12  55  11
39  11  39  11  0   11  38  12

是否有简短的 R 代码来获取此表?

最佳答案

这正是您想要的:

我再次需要社区的帮助 (@akrun) Combining two dataframes with alternating column position

library(dplyr)
df %>% 
  mutate(across(-Score, ~ Score - ., .names = "Score{1:(ncol(df)-1)}")) %>% 
  select(-Score) %>% 
  dplyr::select(all_of(c(matrix(names(.), ncol = ncol(df)-1, byrow = TRUE))))
   I Score1  D Score2  M Score3  N Score4
1 12     10 23     -1 11     11 12     10
2 11     22 11     22 11     22 11     22
3 11     33 11     33 10     34 11     33
4 12     54 11     55 12     54 11     55
5 11     39 11     39 11     39 12     38

关于r - 如何对这些数据进行排序以将特定列与 R 中的其他列相减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72521700/

相关文章:

r - 如何使用整洁的文本使用二元组和三元组

r - 在函数调用中使用变量时,MASS 包中的 glm.nb 链接函数不起作用?

r - C50 在 r 中失败,错误为 "c50 code called exit with value 1"

R:根据列前缀和后缀有条件地替换值

r - R 中的 write.csv 将我的日期转换为 10 位整数

r - Data.Table:重新排列数据时我的代码出错 --R

R 中的 XML 包 - readHTMLTable 和多行类

r - 如何使用函数 usmap 更改 R 中的州或县标签大小?

mysql - 将数据框从 R 插入到 SQL 的有效方法

r - install.packages : unable to move temporary installation 中的警告