Code in R to conditionally subtract columns in data frames

喜夏-厌秋 提交于 2020-08-06 05:20:07

问题


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  ...
 ...          ...            ... ...            ... ...

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             ...
 ...          ...           ...           ...

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!


回答1:


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

data

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))


来源:https://stackoverflow.com/questions/63227341/code-in-r-to-conditionally-subtract-columns-in-data-frames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!