Skip to content

Instantly share code, notes, and snippets.

@fengtan
Last active October 2, 2020 18:33
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/9a510c8c16755ca4b33d25dd8313ecfe to your computer and use it in GitHub Desktop.
Save fengtan/9a510c8c16755ca4b33d25dd8313ecfe to your computer and use it in GitHub Desktop.
#!/usr/bin/env Rscript
# Given:
#
# V | X1 | X2 | X3 | Y1 | Y2 | Y3
# -------------------------------
# A | A | B | C | 2 | 3 | 5 <-- A matches X1, return 2
# B | A | B | B | 6 | 4 | 5 <-- B matches X2,X3, return 4,5
#
# We want:
#
# 2
# 4,5
df <- data.frame(
"V" = c("A", "B"),
"X1" = c("A", "A"),
"X2" = c("B","B"),
"X3" = c("C", "B"),
"Y1" = c(2, 6),
"Y2" = c(3, 4),
"Y3" = c(5, 5)
)
print(df, row.names = FALSE)
fun <- function (row) {
# This vector will collect all values to be returned.
ret = c()
# Extract value in V column.
V <- row[1]
# Get ID of the last X column assuming that:
# - the first column is used by V
# - there are as many X columns as Y columns
# In our example lastXcol is equal to 4.
lastXcol = (length(row)-1)/2+1
# Loop over all X columns.
for (colid in 2:lastXcol) {
# Extract value of the current X column.
X <- row[colid]
# If value in X column == V
if (X == V) {
# Then extract value of the corresponding Y column.
Y <- row[colid+lastXcol-1]
# And put this value in our vector.
ret <- append(ret, Y)
}
}
# Return collected values, glued with a comma.
return(paste(ret, collapse = ","))
}
df2 <- apply(df, 1, fun)
print(df2, row.names = FALSE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment