使用mutate创建带有条件的新列标签 [英] Use mutate to create new column label with conditions
本文介绍了使用mutate创建带有条件的新列标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
过去,我在
df$type[df$variable %in% c("sw.1.", "sw.2.", "sw.3.", "sw.4.", "sw.5.")]<-"water"
df$type[df$variable %in% c("st.1.", "st.2.", "st.3.", "st.4.", "st.5.")]<-"temp"
但现在我正在使用dplyr,并且希望将其插入。但是,我可以无法弄清楚如何使用mutate。这是我的第一枪:
but now I am using dplyr and would like to pipe it in. However, I can't figure out how to do this with mutate. Here is my first shot:
mutate(df, type = ((select(df, starts_with("sw"))) == "temp"))
但它不起作用。
一些示例数据:
plot variable value
3 sw1 4
4 sw1 5
3 sw1 4
4 sw2 2
5 sw2 3
3 st1 4
4 st2 5
5 st1 5
4 st2 2
推荐答案
尝试一下:
> mutate(df, type = c("water", "temp") [
grepl("sw", variable)+2*grepl("st", variable)])
plot variable value type
1 3 sw1 4 water
2 4 sw1 5 water
3 3 sw1 4 water
4 4 sw2 2 water
5 5 sw2 3 water
6 3 st1 4 temp
7 4 st2 5 temp
8 5 st1 5 temp
9 4 st2 2 temp
这使用从两个逻辑向量之和构造的索引。与嵌套ifelse语句相比,可以更紧凑地扩展到更多情况。如果需要,不选择或其他选项可以使该选项成为第一项,并向逻辑向量加1。
This uses indexing constructed from the sum of two logical vectors. Could be extended to more cases more compactly that nested ifelse statements. If wanted a "neither" or "other" option could make that the first item and add 1 to the logical vectors.
这篇关于使用mutate创建带有条件的新列标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文