user236152
user236152

Reputation: 258

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:

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

Upvotes: 0

Views: 69

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102700

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

Upvotes: 1

stefan
stefan

Reputation: 125687

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

Upvotes: 0

Related Questions