如何在R中基于相同坐标值将成对行合并为单行
在R中合并同坐标的两行数据
方法一:用pivot_wider(推荐,tidyverse风格)
先构造和你数据集一致的示例数据,方便直接测试:
library(tidyverse) df <- tibble( Type = c("Pool", "Riffle", "Pool", "Riffle"), Length = c(17.1, 62.1, 82.3, 35.0), Width = c(89.5, 5.8, 79.3, 8.2), `x coord` = c(36.66, 36.66, 35.74, 35.74), `y coord` = c(123.44, 123.44, 127.56, 127.56) )
你之前用pivot_wider没成功,大概率是没给每组的行加区分标识。我们先给每个(x coord, y coord)分组里的行分配序号,再转宽格式:
df_result <- df %>% # 按坐标分组,给每行加序号(1和2) group_by(`x coord`, `y coord`) %>% mutate(row_id = row_number()) %>% ungroup() %>% # 转宽格式,用序号做列后缀 pivot_wider( id_cols = c(`x coord`, `y coord`), names_from = row_id, values_from = c(Type, Length, Width), names_glue = "{.name}{row_id}" ) %>% # 调整列顺序并重命名,匹配你要的格式 select(Type1, Length1, Width1, `x coord`, `y coord`, Type2, Length2, Width2) %>% rename( Type = Type1, Length = Length1, Width = Width1 )
运行后得到的结果就是你想要的格式:
print(df_result) #> # A tibble: 2 × 8 #> Type Length Width `x coord` `y coord` Type2 Length2 Width2 #> <chr> <dbl> <dbl> <dbl> <dbl> <chr> <dbl> <dbl> #> 1 Pool 17.1 89.5 36.7 123. Riffle 62.1 5.8 #> 2 Pool 82.3 79.3 35.7 128. Riffle 35 8.2
方法二:分组后直接合并行(更直观)
如果觉得上面的步骤复杂,也可以用更直白的方式:把每个坐标组的第一行和第二行拆分出来,去掉重复的坐标列后绑定到一起:
df_result2 <- df %>% group_by(`x coord`, `y coord`) %>% group_split() %>% map_dfr(function(group) { # 取第一行作为基础 first_row <- group[1, ] # 取第二行,去掉坐标列并给列名加后缀 second_row <- group[2, ] %>% select(-`x coord`, -`y coord`) %>% rename_with(~paste0(., "2")) # 合并两行 bind_cols(first_row, second_row) })
这个方法逻辑简单,新手更容易理解,结果和方法一完全一致。
内容的提问来源于stack exchange,提问作者blazetooth
相关产品推荐
相关产品推荐

