我有一个测量的数据帧,其中每个测量还测量了背景:
I have a data frame from a measurement where for each measurement a background is also measured:
Wavelength Background_1 1 Background_2 2 ... 300 5 11 4 12 ... 301 3 12 5 10 ... ... ... ... ... ... ...我想减去适当的 Background_xyz从相应的列(例如,从 1减去 Background_1)。然后看起来像这样:
I want to subtract the appropriate "Background_xyz" column from the corresponding column (e.g. subtract "Background_1" from "1". It would then look like this:
Wavelength 1_corrected 2_corrected ... 300 6 8 ... 301 9 5 ... ... ... ... ...我可以做到这一点没有问题,问题是,有时有3个测量值,所以每3列都有背景和真实数据,有时只有1或2我正在寻找一种方法,通过减去与列数无关的背景来获得R正确列,我在想也许 if 函数检查列名可以达到目的,但是我还没有足够的经验来找出解决方法。非常感谢!
I can get this far no problem. The problem is, sometimes there are 3 measurements, so 3 columns with background and "real" data each, sometimes there are only 1 or 2 measurements. I am looking for a way to have R "correct" columns by subtracting the background independent of the number of columns to do so. I was thinking maybe an if function checking for the column names would to the trick but I am not experienced enough to figure out a way to do that yet. Help is greatly appreciated!
推荐答案您首先可以找到只有数字的列使用 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))更多推荐
R中的代码有条件地减去数据帧中的列
发布评论