r - 使用 apply 获取一列的值并计算另一列的值

r - Use apply to take values of one column and calculate values for another column

我有一个包含测量值的数据框。

一列以毫米为单位显示测量值,另一列以单位显示(这是一个相对比例,随我使用的立体显微镜的缩放级别而变化)。 我想遍历数据框的每一行,对于每个等于 NA 的 "length_mm",我想使用 "length_units" 中的值来计算 "length_mm"。

到目前为止,我已经尝试过以下代码:

    convert_to_mm <- function(x) {
      x["length_mm"==NA] <- x["length_units"]/10
      x["length_mm"]
    }
    apply(zooplankton[,c("length_mm","length_units")], 1, convert_to_mm)

有时我也遇到 "length_mm" 和 "length_units" 都等于 NA 的情况。在这些情况下,我只想跳过该行。

快到了。您应该使用 is.na(myVariable) 而不是 myVariable ==NA

这比你做起来容易

# Which are the rows with bad values for mm? Create an indexing vector:
bad_mm <- is.na(zooplankton$length_mm)

# Now, for those rows, replace length_mm with length_units/10
zooplankton$length_mm[bad_mm] <- zooplankton$length_units[bad_mm]/10

记得在检查 NA 值时使用 is.na(x) 而不是 x==NA。为什么?查看 NA==NA 以获得提示!