Use mutate to create new column label with conditi

2019-09-08 05:14发布

问题:

In the past, I created a label in a new column like

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"

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"))

but it doesn't work.

Some example data:

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 

回答1:

Try this:

   > 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

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.



回答2:

We could use ifelse to create the 'type' column

 mutate(df, type= ifelse(variable %in%  paste0('sw', 1:5), 'water', 'temp'))
#  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


标签: r dplyr