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
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.