【问题标题】:R - iterating over rows with if statementsR - 使用 if 语句迭代行
【发布时间】:2023-03-26 10:25:01
【问题描述】:

我正在慢慢自学 R,具有非常基本的编程背景。制作绘图等相对简单,但我目前正在编写一小段代码,目的是构建一个更大的脚本,以减少商业实验室结果的处理——这些通常以相当混乱的 CSV 文件发布,带有不同浓度单位的混合。

所以,我正在尝试生成一个代码块,它遍历包含四个列标题的 CSV 文件的行:“分析物”、“单位”、“LOD”和“浓度”。我打算让我的代码检查每种分析物使用的单位,如果是 mg/l,则将此分析物的浓度转换为 ug/l:

input_file <- read.csv(file="test.csv", header = TRUE,sep = ",")


apply(input_file, 1, function(row) {
  if (input_file$Unit == "mg/l"){
    input_file$Concentration <- input_file$Concentration*1000
  }
  }
  )

print(input_file)

当我运行此代码时(我使用的是 Rstudio),我收到以下错误消息:In if (input_file$Unit == "mg/l") { : the condition has length > 1 and only the first element will be used。我找不到解决方案,而且我对编程术语的有限知识似乎阻碍了这一点。有任何想法吗?任何建议、提示或资源将不胜感激。

【问题讨论】:

    标签: r iteration


    【解决方案1】:

    我相信这是你打算做的:

    apply(input_file, 1, function(row) {
        if (row$Unit == "mg/l"){
            row$Concentration <- row$Concentration*1000
        }
    })
    

    临时变量row代表输入文件的每一行,你要修改的就是这个。

    这是一种更有效的方法:

    input_file[input_file$Unit == "mg/l", "Concentration"] <-
        input_file[input_file$Unit == "mg/l", "Concentration"]*1000
    

    【讨论】:

    • 或许,input_file[input_file$Unit == "mg/l", ]$Concentration &lt;- input_file[input_file$Unit == "mg/l", ]$Concentration * 1000 ?
    • @Symbolix 我的想法完全正确,感谢您的评论。
    猜你喜欢
    • 2019-05-05
    • 2020-11-24
    • 1970-01-01
    • 2011-08-22
    • 2020-10-14
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多