在R中具有特定条件的多个列进行突变

在R中具有特定条件的多个列进行突变

本文介绍了在R中具有特定条件的多个列进行突变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数据

M1  M2  M3 UCL
1   2   3   1.5

我想在这种情况下创建新列:

I would like to make new columns with this condition:

如果M1大于UCL,则MM1将为"UP",否则为"NULL"

If M1 is more than UCL, MM1 will be "UP" and otherwise "NULL"

如果M2大于UCL,则MM2将为"UP",否则为"NULL"

If M2 is more than UCL, MM2 will be "UP" and otherwise "NULL"

如果M3大于UCL,则MM3将为"UP",否则为"NULL"

If M3 is more than UCL, MM3 will be "UP" and otherwise "NULL"

M1  M2  M3 UCL   | MM1  MM2 MM3
1   2   3   1.5  | NULL UP  UP

但是我有几个M列(例如M1〜M1005),所以我想编写一些代码,例如mutate_each和mutate_at.我该如何使用mutate和ifelse函数,以便在特定条件下创建新列?

But I have several M column (like M1~M1005) so that I would like to make some code such as mutate_each and mutate_at. How do I use the function using mutate and ifelse in order to make new columns under a particular condition?

推荐答案

这是一个简单的dplyr解决方案.请注意,将后缀添加到新变量中比较容易,例如获取M1_M而不是MM1.但是,如果您想重命名它们,可以在之后设置colnames(请参见例如有关如何操作).

Here is a simple dplyr solution. Note that it is easier to add a suffix to the new variables e.g. to get M1_M rather than MM1. However, you can set the colnames afterwards if you were keen to rename them (see e.g. here on how to do that).

我将结果显示为tibble,因此您可以看到列类型.请注意,一旦新列中同时包含UPNA,它将从逻辑类型更改为字符类型.

I show the result as a tibble so you can see the column types. Note that once a new column has a both an UP and an NA in it, it will change from a logical type to a character type.

library(dplyr)

textdata <- "M1  M2  M3 UCL
1   2   3   1.5"

mydf <- read.table(text = textdata, header = T)

mydf %>%
    mutate_if(is.integer, as.numeric) %>%
    mutate_at(vars(starts_with("M")), funs(M = ifelse(. > UCL, "UP", NA))) %>%
    tibble::as.tibble()

# A tibble: 1 x 7
     M1    M2    M3   UCL  M1_M  M2_M  M3_M
  <dbl> <dbl> <dbl> <dbl> <lgl> <chr> <chr>
1     1     2     3   1.5    NA    UP    UP

这篇关于在R中具有特定条件的多个列进行突变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 16:56