when pairs of columns across 8 columns that all start with 'to' match the pair of columns in another df make a new column that returns the value in the second dataframe in r

To achieve this in R, you can use a combination of dplyr and stringr packages. Here's a sample code snippet that demonstrates how to accomplish this:

main.r
# Load necessary libraries
library(dplyr)
library(stringr)

# Create sample dataframes
df1 <- data.frame(
  to_column1 = c("value1", "value2", "value3"),
  to_column2 = c("value4", "value5", "value6"),
  to_column3 = c("value7", "value8", "value9"),
  to_column4 = c("value10", "value11", "value12"),
  to_column5 = c("value13", "value14", "value15"),
  to_column6 = c("value16", "value17", "value18"),
  to_column7 = c("value19", "value20", "value21"),
  to_column8 = c("value22", "value23", "value24")
)

df2 <- data.frame(
  to_column1 = c("value1", "value2", "value3"),
  to_column2 = c("value4", "value5", "value6"),
  to_column3 = c("value7", "value8", "value9"),
  to_column4 = c("value10", "value11", "value12"),
  to_column5 = c("value13", "value14", "value15"),
  to_column6 = c("value16", "value17", "value18"),
  to_column7 = c("value19", "value20", "value21"),
  to_column8 = c("value22", "value23", "value24"),
  new_column = c("new_value1", "new_value2", "new_value3")
)

# Get columns that start with 'to' in df1
to_columns <- df1[, str_detect(names(df1), "^to")]

# Initialize an empty dataframe to store results
result <- data.frame()

# Loop through each pair of columns in to_columns
for (i in 1:ncol(to_columns)) {
  # Get the current column
  current_column <- to_columns[, i]
  
  # Get the matching column in df2
  match_column <- df2[[names(to_columns)[i]]]
  
  # Create a new column that returns the value in df2
  new_column <- sapply(current_column, function(x) {
    df2[new_column == x, "new_column"]
  })
  
  # Add the new column to the result dataframe
  result <- cbind(result, new_column)
}

# Bind the result dataframe with the original dataframe
final_result <- cbind(df1, result)

# Print the final result
print(final_result)
1765 chars
57 lines

related categories

gistlibby LogSnag