I have a data frame with a few columns containing values, and a column containing the name of the relevant column. e.g.
df <- data.frame(p1=c("A", "B", "A"),
p2=c("C", "C", "D"),
name=c("p2", "p1", "p1"), stringsAsFactors=FALSE)
What I want to do is to retrieve a value from the column specified by the name field, i.e. the output as below.
> df
p1 p2 name value
1 A C p2 C
2 B C p1 B
3 A D p1 A
I currently get by with df$value <- ifelse(df$name=="p1", df$p1, ifelse(df$name=="p2", df$p2, NA)) , which is inelegant and unscalable if there are more than just p1 and p2.
Any suggestion on a better approach for this?
applyand family doesn't use loops, unlikeforetc?diagone works perfectly but I don't understand what it did. And for my education: whycbind(seq_len(nrow(df))instead of simply1:nrow(df)?seq_lenfor cases with0rows ofdf. Anyway, it is okay for me. I was a bit curious.. Regarding thediag, it would be very inefficient because you are creating a huge dataset and then taking the diagonal.diag, because that is the shortest answer after all.df[,df$$name]creates a dataset with columns based ondf$name. So obviously, many columns are repeated. When you do diag, it extracts the diagonal elements