清单中的which.max结果

时间:2019-01-31 05:54:01

标签: r max

编辑:请参阅底部的解决方案。

在列表中使用which.max结果的结果时遇到麻烦。 下面的示例重现了我的问题。

创建数据框

library(dplyr)
library(ggplot2)
library(forcats)

name <- c('A','A','A', 'A','A','A', 'A','A','A', 
          'B','B','B', 'B','B','B', 'B','B','B',
          'C','C','C', 'C','C','C', 'C','C','C')
month = c("oct 2018", "oct 2018", "oct 2018","nov 2018", "nov 2018", "nov 2018","dec 2018", "dec 2018", "dec 2018",
         "oct 2018", "oct 2018", "oct 2018","nov 2018", "nov 2018", "nov 2018","dec 2018", "dec 2018", "dec 2018" ,
         "oct 2018", "oct 2018", "oct 2018","nov 2018", "nov 2018", "nov 2018","dec 2018", "dec 2018", "dec 2018" )
value <- seq(1:length(month))

df = data.frame(name, month, value)
df

结果

name    month   value
A   oct 2018    1
A   oct 2018    2
A   oct 2018    3
A   nov 2018    4
A   nov 2018    5
A   nov 2018    6
A   dec 2018    7
A   dec 2018    8
A   dec 2018    9
B   oct 2018    10
B   oct 2018    11
B   oct 2018    12
B   nov 2018    13
B   nov 2018    14
B   nov 2018    15
B   dec 2018    16
B   dec 2018    17
B   dec 2018    18
C   oct 2018    19
C   oct 2018    20
C   oct 2018    21
C   nov 2018    22
C   nov 2018    23
C   nov 2018    24
C   dec 2018    25
C   dec 2018    26
C   dec 2018    27 

提取具有最大值的观测名称

memberLargestValue = df[which.max(df$value),]$name
memberLargestValue

结果

[1] C
Levels: A B C

将memberLargestValue与预先存在的列表合并

oldList = c("A", "A")
newList  = c(oldList, memberLargestValue)
newList

结果

[1] "A" "A" "3"

我不希望上面的列表中有“ 3”,但我希望有“ C”。有人知道如何在“ memberLargestValue”中添加“ C”并将其放入列表吗?

解决方案: 更改为“字符”类型:

memberLargestValue = as.character(df[which.max(df$value),]$name)

0 个答案:

没有答案