我在 R tidyverse 中有一个数据集,我想根据与 sp 列的比较创建 192 列,就像 mp_comp_1 列一样。如何对 tidyverse 中的 192 列执行此操作?
library(tidyverse)
df <- data.frame(matrix(ncol = 4, nrow = 3))
df%>%
mutate(sp = c(34.9, 34.3, 34.4)) %>%
mutate(mp_1 = c(35, 32.1, 34.4)) %>%
mutate(mp_2 = c(30, 38.1, 39.4)) %>%
mutate(mp_192 = c(34.9, 34.3, 30.4)) %>%
select(sp, mp_1, mp_2, mp_192) %>%
mutate(mp_comp_1= if_else(mp_1>sp, "bigger",
if_else(mp_1<sp, "smaller", "equal")))
您可以使用
across
和 case_when
。
library(dplyr)
df |>
mutate(across(starts_with("mp_"),
~case_when(.x > sp ~ "bigger",
.x < sp ~ "smaller",
.x == sp ~ "equal"),
.names = "{.col}_comp"))
sp mp_1 mp_2 mp_192 mp_1_comp mp_2_comp mp_192_comp
1 34.9 35.0 30.0 34.9 bigger smaller equal
2 34.3 32.1 38.1 34.3 smaller bigger equal
3 34.4 34.4 39.4 30.4 equal bigger smaller
df <- structure(list(sp = c(34.9, 34.3, 34.4), mp_1 = c(35, 32.1, 34.4
), mp_2 = c(30, 38.1, 39.4), mp_192 = c(34.9, 34.3, 30.4)), class = "data.frame", row.names = c(NA,
-3L))