R计算两列所有值之间的差异

R calculate difference between all values of two columns

如何计算两列的所有值之间的差异。

X Mass_1  Mass_2
1 109.8    203.4  
2 306.7    305.5
3 658.7    446.5

我需要 Mass_1 与 Mass_2

的所有数字的差值
> X  Mass_1        Mass_2_1         Mass_2_2     Mass_2_3       
> 1   109.8      (109.8-203.4)    (109.8-305.5)   (109.8-446.5) 
> 2   306.7      (306.7-203.4)    (306.7-305.5)   (306.7-446.5) 
> 3   658.7      (658.7-203.4)    (658.7-305.5)   (658.7-446.5)

您可以使用 lapply -

cols <- paste0('Mass_2_', seq(nrow(df)))
df[cols] <- lapply(df$Mass_2, function(x) df$Mass_1 - x)
df

#  X Mass_1 Mass_2 Mass_2_1 Mass_2_2 Mass_2_3
#1 1  109.8  203.4    -93.6   -195.7   -336.7
#2 2  306.7  305.5    103.3      1.2   -139.8
#3 3  658.7  446.5    455.3    353.2    212.2

或者用 outer -

df[cols] <- outer(df$Mass_1, df$Mass_2, `-`)

数据

df <- structure(list(X = 1:3, Mass_1 = c(109.8, 306.7, 658.7), Mass_2 = c(203.4, 
305.5, 446.5)), class = "data.frame", row.names = c(NA, -3L))