我有一个包含18列的数据集,我需要从中返回每个观察值具有最高值的列名,下面是一个简单的示例。我遇到了this的答案,它几乎可以满足我的需要,但是在某些情况下,我需要组合名称(例如下面ab
中的maxcol
)。我该怎么办?
任何建议将不胜感激!如果可能的话,对我来说,基于tidyverse的解决方案会更容易理解,因为我比基础更熟悉。
编辑:我忘了提到数据中的某些列具有NAs。
library(dplyr, warn.conflicts = FALSE)
#turn this
Df <- tibble(a = 4:2, b = 4:6, c = 3:5)
#into this
Df <- tibble(a = 4:2, b = 4:6, c = 3:5, maxol = c("ab", "b", "b"))
由reprex package(v0.2.1)于2018-10-30创建
答案 0 :(得分:2)
从linked post的答案继续,我们可以做
Df$maxcol <- apply(Df, 1, function(x) paste0(names(Df)[x == max(x)], collapse = ""))
Df
# a b c maxcol
# <int> <int> <int> <chr>
#1 4 4 3 ab
#2 3 5 4 b
#3 2 6 5 b
对于每一行,我们检查哪个位置具有最大值,并且paste
和names
共同位于该位置。
如果您喜欢tidyverse
方法
library(tidyverse)
Df %>%
mutate(row = row_number()) %>%
gather(values, key, -row) %>%
group_by(row) %>%
mutate(maxcol = paste0(values[key == max(key)], collapse = "")) %>%
spread(values, key) %>%
ungroup() %>%
select(-row)
# maxcol a b c
# <chr> <int> <int> <int>
#1 ab 4 4 3
#2 b 3 5 4
#3 b 2 6 5
我们首先使用gather
将数据帧从宽转换为长,然后将group_by
的每一行paste
的列max
key
转换为{{1 }}长数据框再次变宽。