Home > database >  How can I create a new column with values 1/0, where the value in the new column is 1 only if values
How can I create a new column with values 1/0, where the value in the new column is 1 only if values

Time:01-19

I have two columns within a DF, "wet" and "cold", with values of 1 and 0 respectively, e.g:

Wet Cold
1     1
0     1
0     1
1     0
1     1
0     0

I would like to create a new column, wet&cold, where only if wet=1 and cold=1, then wet&cold=1. If any or both of them are 0 or not matching, then wet&cold=0.

I tried to work around with grepl, but without success.

CodePudding user response:

Base R solution

df$`wet&cold` <- df$Wet*df$Cold
df

  Wet Cold wet&cold
1   1    1        1
2   0    1        0
3   0    1        0
4   1    0        0
5   1    1        1
6   0    0        0

dplyr solution

df %>%
  mutate(`wet&cold`=Wet*Cold)

  Wet Cold wet&cold
1   1    1        1
2   0    1        0
3   0    1        0
4   1    0        0
5   1    1        1
6   0    0        0

CodePudding user response:

Another option by checking I all row values have the value 1 for all the columns and convert the TRUE/FALSE to 1/0 with as.integer like this:

df$wet_cold = as.integer(rowSums(df == 1) == ncol(df))
df
#>   Wet Cold wet_cold
#> 1   1    1        1
#> 2   0    1        0
#> 3   0    1        0
#> 4   1    0        0
#> 5   1    1        1
#> 6   0    0        0

Created on 2023-01-18 with reprex v2.0.2

CodePudding user response:

Other solution works great with the clever multiplication. Here's perhaps a more general solution using ifelse(), which works well for this two case situation.

df <- data.frame(
    wet = c(1, 0, 0, 1, 1, 0),
    cold = c(1, 1, 1, 0, 1, 0)
)

df$wet_cold <- ifelse(df$wet == 1 & df$cold == 1, 1, 0)

df

#     df
#   wet cold wet_cold
# 1   1    1        1
# 2   0    1        0
# 3   0    1        0
# 4   1    0        0
# 5   1    1        1
# 6   0    0        0
  • Related