You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R提取植物生长得分跃迁日期及首值对应列名?

用R自动化处理植物生长阶段数据

1. 查找每行指定数值首次出现的列名

可以通过自定义函数结合apply()实现,直接返回对应列名(即观测日期)。

代码实现

# 定义函数:输入一行数据和目标数值,返回首次出现该数值的列名
first_occur_col <- function(row, target_val) {
  col_names <- names(row)
  # 找到目标数值首次出现的位置
  first_pos <- match(target_val, row)
  # 处理未找到的情况(返回NA)
  ifelse(is.na(first_pos), NA, col_names[first_pos])
}

# 假设你的数据集名为growth_data,行是单株植物,列是观测日期
# 示例:提取每行中数值1首次出现的日期,生成新列
growth_data$first_score_1 <- apply(growth_data, 1, first_occur_col, target_val = 1)

2. 提取生长得分跃迁对应的观测日期

根据植物生长得分从0→1、1→2…4→5的跃迁需求,分两种场景处理:

场景1:得分仅单向递增(无下降)

若植物生长得分只会上升不会回落,跃迁日期等价于下一级得分首次出现的日期,可基于第一部分的函数批量提取:

# 创建存储各得分首次出现日期的数据集
score_first_dates <- data.frame(
  plant_id = rownames(growth_data),
  first_0 = NA, first_1 = NA, first_2 = NA,
  first_3 = NA, first_4 = NA, first_5 = NA
)

# 循环提取每个得分的首次出现日期
for (score in 0:5) {
  col_name <- paste0("first_", score)
  score_first_dates[[col_name]] <- apply(growth_data, 1, first_occur_col, target_val = score)
}

# 计算各跃迁对应的日期
score_first_dates$transition_0to1 <- score_first_dates$first_1
score_first_dates$transition_1to2 <- score_first_dates$first_2
score_first_dates$transition_2to3 <- score_first_dates$first_3
score_first_dates$transition_3to4 <- score_first_dates$first_4
score_first_dates$transition_4to5 <- score_first_dates$first_5

场景2:得分可能出现波动(偶尔下降)

若存在得分回落的情况,需要精准定位首次从k变为k+1的观测日期(即当前值为k+1且前一个值为k):

# 创建存储跃迁日期的数据集
transition_dates <- data.frame(plant_id = rownames(growth_data))

# 循环处理每个跃迁阶段
for (k in 0:4) {
  transition_col <- paste0("transition_", k, "to", k+1)
  transition_dates[[transition_col]] <- apply(growth_data, 1, function(row) {
    # 遍历每行的观测值(从第2个开始,对比前一个值)
    for (i in 2:length(row)) {
      if (row[i-1] == k && row[i] == k+1) {
        return(names(row)[i])
      }
    }
    # 未找到跃迁则返回NA
    return(NA)
  })
}

内容的提问来源于stack exchange,提问作者Steven Spivak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 14:15:39