I have a df where I want to add a column depending on the contents of other columns. I have it working for one sample with:
df <- df %>%
mutate(SB013 = if_else(sample_id == "SB013", IN, OUT))
Where I add a column called SB013, if the row in sample_id column == "SB013" then add the contents of column IN else add the contents of column OUT. I now need to expand this to add more columns for the number of sample_ids there are. So:
sample_names<- unique(df$sample_id)
sample_names
[1] "SB013" "SB014" "SB015" "SB016"
I have tried a couple of for loops:
for (name in sample_names) {
comb.variant <- comb.variant %>%
mutate(name = if_else(sample_id == name, Alt,Ref))
}
Where only one column called "name" is added. And:
for (i in 1:length(sample_names)) {
#print(sample_names[i])
comb.variant <- comb.variant %>%
mutate(sample_names[i] = if_else(sample_id == sample_names[i], Alt,Ref))
}
Error: unexpected '=' in:
" comb.variant <- comb.variant %>%
mutate(sample_names[i] ="
How do I make this work??
See Question&Answers more detail:os