如何找到最大值具有前一个if语句的特定行中的值,用于确定该特定行

时间:2018-04-18 18:24:40

标签: r if-statement max

希望我所陈述的问题不会产生误导。

我想弄清楚的是,让我们说数据文件看起来与此类似:

id; name; values
1;alpha;0.5;0.78;0.945
2;beta;0.2;0.023;0.4
3;gamma;0.78;1.342;4.123
4;delta;2.1;4.90;0.89

...

基于给定的名称,假设“gamma”应该确定与gamma有关的最大值,因此4.123。在我的情况下,我有几个文件,我想应用for循环,但我正在努力解决如何为gamma设置if语句的问题。

感谢您的帮助。

干杯, 奥利

2 个答案:

答案 0 :(得分:0)

var gamma = [0.78,1.342,4.123];

var largest;

for (i = 0; i < gamma .length; i++) {
    if (gamma[i] > largest) {
        largest = gamma[i];
    }
}

答案 1 :(得分:0)

基于使用库dplyr和reshape2整理数据帧概念的解决方案

# create test data - note that there are not full column names .. so skip
# the headin row and add headers later

df <- read.table(text = "id; name; values
1;alpha;0.5;0.78;0.945
2;beta;0.2;0.023;0.4
3;gamma;0.78;1.342;4.123
4;delta;2.1;4.90;0.89
", 
  sep = ";", skip = 1)

# library reshape2 for function meltto make a tall dataframe ... (library
# tidyr (also tidyverse) has similar functions gather/spread)
library(reshape2)
#> Warning: package 'reshape2' was built under R version 3.4.3
# library dplyr for summarization/manipulation
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

# make into a tall, tidy data set (key value pairs)
df_tidy <- melt(df, id.vars = c("V1", "V2"))

# rename the columns
names(df_tidy) <- c("id", "name", "variable", "value")
df_tidy
#>    id  name variable value
#> 1   1 alpha       V3 0.500
#> 2   2  beta       V3 0.200
#> 3   3 gamma       V3 0.780
#> 4   4 delta       V3 2.100
#> 5   1 alpha       V4 0.780
#> 6   2  beta       V4 0.023
#> 7   3 gamma       V4 1.342
#> 8   4 delta       V4 4.900
#> 9   1 alpha       V5 0.945
#> 10  2  beta       V5 0.400
#> 11  3 gamma       V5 4.123
#> 12  4 delta       V5 0.890

# summarize grabbing the top 1 value per group
result <- df_tidy %>% group_by(name) %>% top_n(1, value)

result
#> # A tibble: 4 x 4
#> # Groups:   name [4]
#>      id   name variable value
#>   <int> <fctr>   <fctr> <dbl>
#> 1     4  delta       V4 4.900
#> 2     1  alpha       V5 0.945
#> 3     2   beta       V5 0.400
#> 4     3  gamma       V5 4.123

# now for a particular value
result %>% filter(name == "gamma") %>% select(name, value)
#> # A tibble: 1 x 2
#> # Groups:   name [1]
#>     name value
#>   <fctr> <dbl>
#> 1  gamma 4.123