Created
May 31, 2019 20:07
-
-
Save fengtan/b08ff4b1d7ac6db938ca0dbcf1f21b67 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env Rscript | |
df <- data.frame( | |
"V" = c("A", "B"), | |
"X" = c("A", "A"), | |
"Y" = c("B","B"), | |
"Z" = c("B", "C"), | |
"X1" = c(2, 4), | |
"Y2" = c(3,4), | |
"Z3" = c(5, 5) | |
) | |
print(df, row.names = FALSE) | |
fun <- function (row, colnames) { | |
# Loop over columns (except first column) | |
for (colid in 2:length(colnames)) { | |
# If value in current column == value in first column | |
if (row[colid] == row[1]) { | |
# Then get the name of the current column | |
return(colnames[colid]) | |
} | |
} | |
} | |
df2 <- apply(df, 1, fun, colnames = colnames(df)) | |
print(df2, row.names = FALSE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment