Skip to content

Instantly share code, notes, and snippets.

@fengtan
Created May 31, 2019 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fengtan/b08ff4b1d7ac6db938ca0dbcf1f21b67 to your computer and use it in GitHub Desktop.
Save fengtan/b08ff4b1d7ac6db938ca0dbcf1f21b67 to your computer and use it in GitHub Desktop.
#!/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