Create new column dplyr

In dplyr, you can create a new column using the mutate() function. Here's a basic example:

library(dplyr)

# create a sample dataframe
df <- data.frame(x = 1:5, y = 2:6)

# create a new column 'z' by multiplying 'x' and 'y'
df %>% mutate(z = x * y)

This will create a new column z in the dataframe df with the values 2, 4, 6, 8, 10.

You can also use other functions like ifelse(), case_when(), rowSums(), rowMeans() etc. to create the new column based on the conditions or calculations.

For example, to create a new column z with the values 1 if x is greater than 3, and 0 otherwise:

df %>% mutate(z = ifelse(x > 3, 1, 0))

Or to create a new column z with the sum of x and y:

df %>% mutate(z = rowSums(cbind(x, y)))

You can also use mutate() with other dplyr functions like group_by(), filter(), arrange() etc. to create new columns based on the grouped data, filtered data, or sorted data.