r add column to dataframe based on other columns code example

Example 1: change column value based on another column pandas

# Changes the 'is_electric' column based on value in the 'type' column
# If the 'type' column == 'electric' then the 'is_electric' becomes 'YES'
df['is_electric']= df['type'].apply(lambda x: 'YES' if (x == 'electric') else 'NO')

Example 2: r change column based on condition

# If a condition is met in a specific column (column "b" is 0), 
# change the value in column "est". Here the value is replaced
# by the value for "a" in that same row where b == 0.

df$est[df$b == 0] <- df$a[df$b == 0]

Tags:

R Example