简体   繁体   中英

Dplyr mutate using existing columns

I have this DF in R:

species <- c("dac", "dac", "theo",  "syl")
label <- c("dac1", "dac2", "gna", "gni")
df <- data.frame(species, label)

I want to create a new column (called pop) where:

  • if species == "dac", it would use put the corresponding value in the "label" column
  • else, it would put the corresponding value from the "species" column

Result look like this:

pop <- c("dac1", "dac2", "theo",  "syl")
df2 <- data.frame(species, label, pop)

I unfortunately don't manage to have this working using if else and mutate. Can you help?

Thanks!

M

Her is ab base R option

within(df,pop <- ifelse(species == "dac",label,species))

or

within(df,pop <- df[cbind(1:nrow(df),ifelse(species == "dac",2,1))])

which gives

  species label  pop
1     dac  dac1 dac1
2     dac  dac2 dac2
3    theo   gna theo
4     syl   gni  syl

Try this:

library(dplyr)
species <- c("dac", "dac", "theo",  "syl")
label <- c("dac1", "dac2", "gna", "gni")
df <- data.frame(species, label)

pop <- c("dac1", "dac2", "theo",  "syl")
df2 <- data.frame(species, label, pop)

mutate(df, pop = if_else(species == "dac", label, species))
#>   species label  pop
#> 1     dac  dac1 dac1
#> 2     dac  dac2 dac2
#> 3    theo   gna theo
#> 4     syl   gni  syl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM