In my data frame, I have columns, some columns have integers but some columns have single characters in each row. I want it so that if the character of one column matches the character of the other column in the same row, it should say 1 in the same row in another column with currently only zeros in it. And I want R to do this for each row of the three columns
CodePudding user response:
You didn't provide any data, but I think you want:
library(dplyr)
df <- data.frame(col1 = c("a","b","c"),
col2 = c("a", "a", "c"))
df <- df %>% mutate(col3 = ifelse(col1 == col2, 1,0))
CodePudding user response:
In base R, you could consider the following.
First, I made up sample data to use as an example:
set.seed(17)
df <- data.frame(
x = sample(letters[1:5], 8, replace = T),
y = sample(letters[1:5], 8, replace = T),
z = 0
)
df
x y z
1 b b 0
2 a d 0
3 d e 0
4 e c 0
5 b d 0
6 a a 0
7 d e 0
8 a b 0
You can get a logical vector that would describe which rows had the same character value for columns x
and y
:
df$x == df$y
[1] TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE
Here, rows 1 and 6 are TRUE
, where the values match.
Then, you can replace the third column z
with 1 for those rows:
df[df$x == df$y, "z"] <- 1
df
x y z
1 b b 1
2 a d 0
3 d e 0
4 e c 0
5 b d 0
6 a a 1
7 d e 0
8 a b 0