更新时间:2022-12-10 13:36:13
这是一个简单的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
,因此您可以看到列类型.请注意,一旦新列中同时包含UP
和NA
,它将从逻辑类型更改为字符类型.
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