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

编程入门 行业动态 更新时间:2024-10-08 05:36:03
本文介绍了R中的代码有条件地减去数据帧中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个测量的数据帧,其中每个测量还测量了背景:

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中的代码有条件地减去数据帧中的列

本文发布于:2023-11-22 08:08:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616616.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   代码   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!