迭代获取数据框列的最大值,加一并重复 r 中的所有行

Iteratively get the max of a data frame column, add one and repeat for all rows in r

我需要执行一个数据库操作,我将向现有 table 添加新数据,然后为新行分配一个唯一 ID。我在 R 中询问这个问题,这样我就可以在尝试在 sql 或 pyspark.

中重写它之前弄清楚逻辑。

假设我已经将新数据添加到现有数据中。这是它可能看起来像的简化版本:

library(tidyverse)

df <- tibble(id = c(1, 2, 3, NA, NA),
             descriptions = c("dodgers", "yankees","giants", "orioles", "mets"))

# A tibble: 5 x 2
     id descriptions
  <dbl> <chr>       
1     1 dodgers     
2     2 yankees     
3     3 giants      
4    NA orioles     
5    NA mets 

我想要的是:

# A tibble: 5 x 2
     id descriptions
  <dbl> <chr>       
1     1 dodgers     
2     2 yankees     
3     3 giants      
4     4 orioles     
5     5 mets 

我无法使用 arrangerowid_to_columns id 被删除。

要在不更改现有行的情况下为 NA 行获取唯一 ID,我想获取 id 列的最大值,添加一个,用该值替换 NA,然后移动到下一个排。我的直觉是做这样的事情: df %>% mutate(new_id = max(id, na.rm = TRUE) + 1) 但那只会得到最大值加一,而不是每行的新最大值。我觉得我可以用映射函数来做到这一点,但我试过 returns 结果与输入数据帧相同:

df %>% 
  mutate(id = ifelse(is.na(id),
                     map_dbl(id, ~max(.) + 1, na.rm = FALSE),
                     id))

# A tibble: 5 x 2
     id descriptions
  <dbl> <chr>       
1     1 dodgers     
2     2 yankees     
3     3 giants      
4    NA orioles     
5    NA mets  

在此先感谢--现在如果有人可以在 sql 中直接帮助我,那也是加分项!

这是一种方法,我们将 max 值与基于 NA 值的逻辑向量的累积和相加,并将 coalesce 与原始列 'id'

library(dplyr)
df <- df %>% 
   mutate(id =  coalesce(id, max(id, na.rm = TRUE) + cumsum(is.na(id))))

-输出

df
# A tibble: 5 x 2
     id descriptions
  <dbl> <chr>       
1     1 dodgers     
2     2 yankees     
3     3 giants      
4     4 orioles     
5     5 mets       

SQL 选项,使用 sqldf 进行演示:

sqldf::sqldf("
  with cte as (
    select max(id) as maxid from df
  )
  select cte.maxid + row_number() over () as id, df.descriptions
  from df
    left join cte where df.id is null
  union
  select * from df where id is not null")
#   id descriptions
# 1  1      dodgers
# 2  2      yankees
# 3  3       giants
# 4  4      orioles
# 5  5         mets