【问题标题】:Consolidate rows and take minimum and maximum values合并行并取最小值和最大值
【发布时间】:2021-02-03 18:24:21
【问题描述】:

我想知道这样做的最佳方法是什么。

我有一个 csv 表,其中包含 3 列的超过 50 万个条目。我注意到有些行有多个开始和结束位置。我想将它们合并到一行中,并为它们的范围取最小值和最大值。

我想知道我该怎么做。我正在考虑使用R?我愿意接受任何建议。提前谢谢你。

A,10,200
A,250,350
B,5,220
B,230,260
C,1,100
D,20,50
E,1,10
F,11,90
F,100,200
F,210,350
etc

我希望最终的结果是这样的:

A,10,350
B,5,260
C,1,100
D,20,50
E,1,10
F,11,350

【问题讨论】:

  • 可以去掉python标签

标签: r


【解决方案1】:

这通过将您的两个数字列转换为一列来实现。这样您就可以将minmax 放在一个列上,即value

library(tidyr)
library(dplyr)

df %>% 
  tidyr::pivot_longer(cols = c(B, C)) %>%
  dplyr::group_by(A) %>% 
  dplyr::summarize(min = min(value),
                   max = max(value))

  A       min   max
  <chr> <int> <int>
1 A        10   350
2 B         5   260
3 C         1   100
4 D        20    50
5 E         1    10
6 F        11   350

数据

lines <- "
A,B,C
A,10,200
A,250,350
B,5,220
B,230,260
C,1,100
D,20,50
E,1,10
F,11,90
F,100,200
F,210,350"

df <- read.table(text = lines, header = T, sep = ",")

【讨论】:

  • 不幸的是我收到了这个错误:Error: Evaluation error: could not find function "c_across". 有什么想法吗?
  • @ZA786 此解决方案不使用c_across。但是,如果您在 dplyr 包中加载了 library(dplyr),则可能是版本问题。 c_across 是 1.0.0 版的新内容。你可以通过packageVersion("dplyr")查看你的版本。
  • 谢谢你,成功了。我必须更新 dplyr ... 还有什么方法可以保留将所有内容更改为字母顺序的顺序?
  • @ZA786 原始问题中提供的数据按字母顺序排列。
【解决方案2】:

R中,我们可以按第一列和summarisec_across分组,以根据其他列返回minmax

library(dplyr)    
df1 %>%
  group_by(col1) %>% 
  summarise(min = min(c_across(everything())), 
             max = max(c_across(everything())), .groups = 'drop')

-输出

# A tibble: 6 x 3
#  col1    min   max
#  <chr> <int> <int>
#1 A        10   350
#2 B         5   260
#3 C         1   100
#4 D        20    50
#5 E         1    10
#6 F        11   350

数据

df1 <- structure(list(col1 = c("A", "A", "B", "B", "C", "D", "E", "F", 
"F", "F"), col2 = c(10L, 250L, 5L, 230L, 1L, 20L, 1L, 11L, 100L, 
210L), col3 = c(200L, 350L, 220L, 260L, 100L, 50L, 10L, 90L, 
200L, 350L)), class = "data.frame", row.names = c(NA, -10L))

【讨论】:

  • 不幸的是,我收到了以下错误:Error: 'pivot_longer' is not an exported object from 'namespace:tidyr' 有什么想法吗?
  • @ZA786 你可能有一个旧版本的tidyr。你能更新你的tidyr 包吗
  • 谢谢你,成功了。我不得不更新 tidyr ... 还有什么方法可以保留将所有内容更改为字母顺序的顺序?
  • @ZA786 在示例中,第一列的值似乎是 A 到 F
猜你喜欢
  • 2017-08-01
  • 1970-01-01
  • 2020-08-06
  • 2020-01-12
  • 2017-06-24
  • 2016-06-14
  • 1970-01-01
  • 2014-02-22
  • 1970-01-01
相关资源
最近更新 更多