【问题标题】:Add the corresponding maximum value in a new column for each month在每个月的新列中添加相应的最大值
【发布时间】:2019-10-30 11:41:15
【问题描述】:

我有以下数据框:

df <- structure(list(locality_id = structure(c(3L, 1L, 2L, 4L), .Label = c("L2762894", 
"L3064193", "L6199859", "L8044094"), class = "factor"), month = structure(c(1L, 
3L, 1L, 2L), .Label = c("1", "2", "3"), class = "factor"), prec01 = c(105, 
109, 133, 79), prec02 = c(29, 34, 34, 35), prec03 = c(18, 48, 
42, 184)), class = "data.frame", row.names = c(NA, -4L))

每个locality 都有第一个three months (prec01, prec02, prec03)precipitation 值。

我想创建一个唯一的降水列,将每个月的对应降水值匹配到对应的月份(列月)。结果如下:

#   locality_id month prec
# 1    L6199859     1  105
# 2    L2762894     3  109
# 3    L3064193     1  133
# 4    L8044094     2  184

知道如何产生上述输出吗?

谢谢!

【问题讨论】:

标签: r dataframe match


【解决方案1】:

如果我理解您的问题,您想在新的prec 列中保留precXX 对应的month 值吗?

在这种情况下,在我看来,这个例子是不正确的,而应该是:

起始数据框:

  locality_id month prec01 prec02 prec03
1    L6199859     1    105     29     18
2    L2762894     3    109     34     48
3    L3064193     1    133     34     42
4    L8044094     2     79     35    184

最终数据框:

 locality_id month prec
1    L6199859     1  105
2    L2762894     3   48
3    L3064193     1  133
4    L8044094     2   35

您可以通过矩阵索引来实现:

i <- as.numeric(df$month)

df$prec <- df[,c(3,4,5)][cbind(seq_along(i), i)]

df[,c(-3,-4,-5)]

【讨论】:

    猜你喜欢
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多