且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

R中的代码有条件地减去数据帧中的列

更新时间:2022-12-20 11:35:43

您首先可以找到只有数字的列使用 grep ,则可以获取相应的背景 列并减去。

You can first find the columns which have only numbers using grep, you can then get the corresponding "Background" columns and subtract.

cols <- grep('^\\d+$', names(df), value = TRUE)
new_cols <- paste0(cols, '_corrected')
df[new_cols] <- df[cols] - df[paste0('Background_', cols)]
df[c("Wavelength", new_cols)]

#  Wavelength 1_corrected 2_corrected
#1        300           6           8
#2        301           9           5

数据

df <- structure(list(Wavelength = 300:301, Background_1 = c(5L, 3L), 
`1` = 11:12, Background_2 = 4:5, `2` = c(12L, 10L)), 
class = "data.frame", row.names = c(NA, -2L))