-1

New to R here and even coding. I have a character vector "change" in dataframe "df" that is made of values that I know require the input from an adjacent column.

change <- c("Apple","Bananas","Cheese")

I want to make it so in a new column "New" if the value in "ColumnA" matches any value in "change", then it gives me the value in "ColumnB", else it returns the value in "Column A".

╔══════════╦════════════╦════════════╗
║ ColumnA  ║  ColumnB   ║    New     ║
╠══════════╬════════════╬════════════╣
║ Apples   ║ ApplesNew  ║ ApplesNew  ║
║ Beer     ║ BeerNew    ║ Beer       ║
║ Bananas  ║ BananasNew ║ BananasNew ║
║ Bananas  ║ BananasNew ║ BananasNew ║
║ Cheese   ║ CheeseNew  ║ CheeseNew  ║
╚══════════╩════════════╩════════════╝

I tried this:

within(df, {
    New <- ifelse(ColumnA %in% change, ColumnB, ColumnA)
}
)

Thanks in advance.

nawklea
  • 23
  • 7

1 Answers1

0

Try this:

# Your sample data
change <- c("Apples","Bananas","Cheese");
    df <- cbind.data.frame(
    ColumnA = c("Apples", "Beer", "Bananas", "Bananas", "Cheese"),
    ColumnB = c("ApplesNew", "BeerNew", "BananasNew", "BananasNew", "CheeseNew")
);

within(df, { New = ifelse(ColumnA %in% change, as.character(ColumnB), as.character(ColumnA)) })
#  ColumnA    ColumnB        New
#1  Apples  ApplesNew  ApplesNew
#2    Beer    BeerNew       Beer
#3 Bananas BananasNew BananasNew
#4 Bananas BananasNew BananasNew
#5  Cheese  CheeseNew  CheeseNew

If you don't do as.character(...), the column will contain the factor numbers instead.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68