首页 > 解决方案 > 使用 tidyverse 循环所有行并仅识别(并保留)较高的值

问题描述

我正在与心理学领域的人一起工作,因子分析是该领域的典型程序。我有一个如下数据集:

原始数据集

我想只保留每行中的最大值,同时在丢​​失的情况下转换所有其他值

新数据集

我知道 dplyr 可以轻松解决这个问题,但我找不到一个简单的代码示例来执行它。

请检查下面的代码以重现此问题:

library(tidyverse)
set.seed(123)
ds <- data.frame(x1 = runif(10,min = .1,.29),x2 = runif(10,min = .1,.35), x3 = runif(10,min = .1,.38))
ds <- ds %>% mutate_all(funs(round(.,3)))

ds 

请记住,这个问题可以帮助其他有相同(或类似)问题的人。我在询问之前进行了搜索,我在这里只找到了一个紧密的话题

非常感谢。

标签: rloopsdplyrtidyverse

解决方案


一个非常快速的答案是:

pmax(base) 函数用于逐行最大值,然后mutate_all使用if_else要保留或设置为缺失的语句

ds %>% 
  #find the row-wise maximum and store it as a column temporarily
  mutate (max = pmax(x1,x2,x3)) %>% 
  #loop through all columns and do a check whether the value equals the max
  #If Yes, then leave as is, if not then set to NA
  mutate_all( funs(if_else(. == max,max,NA_real_))) %>% 
  #remove the temporary `max` column
  select(-max)

      x1    x2    x3
1     NA    NA 0.349
2     NA    NA 0.294
3     NA    NA 0.279
4     NA    NA 0.378
5     NA    NA 0.284
6     NA 0.325    NA
7     NA    NA 0.252
8  0.270    NA    NA
9  0.205    NA    NA
10    NA 0.339    NA

推荐阅读