Update row values based on condition in R

I am trying to update the values of Column C2 and C3 based on conditions:

• The variable C2 is equal to 1 if the type of cue = 2, and 0 otherwise.

• The variable C3 is equal to 1 if the type of cue = 3, and 0 otherwise.

Data frame Image: https://drive.google.com/file/d/1Enik09cXQ21d3cQQv0_YQDZGBb3Btm5n/view?usp=sharing

dput(Cognitive[1:6,]) = 
structure(list(Subject = c(1L, 1L, 1L, 1L, 1L, 1L), Time = c(191L, 
206L, 219L, 176L, 182L, 196L), W = c(0L, 0L, 0L, 1L, 1L, 1L), 
    Cue = c(1L, 2L, 3L, 1L, 2L, 3L), D = c(0L, 0L, 0L, 0L, 0L, 
    0L), Subject.f = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1", 
    "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", 
    "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", 
    "23", "24"), class = "factor"), Cue.f = structure(c(1L, 2L, 
    3L, 1L, 2L, 3L), .Label = c("1", "2", "3"), class = "factor"), 
    D.f = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("0", 
    "1"), class = "factor"), C2 = structure(c(1L, 2L, 3L, 1L, 
    2L, 3L), .Label = c("1", "2", "3"), class = "factor"), C3 = structure(c(1L, 
    2L, 3L, 1L, 2L, 3L), .Label = c("1", "2", "3"), class = "factor")), row.names = c(NA, 
6L), class = "data.frame")

Cognitive <- read.csv(file = 'Cognitive.csv')
View(Cognitive)

# Factor the variables Subject, Cue and D and add these variable to the Cognitive data frame.
Cognitive <- mutate(Cognitive, Subject.f = factor(Subject), Cue.f = factor(Cue), D.f = factor(D))

Cognitive <- mutate(Cognitive, C2 = Cue.f, C3 = Cue.f)

Thanks.

Upvotes: 0

Views: 1755

Answers (3)

akrun
akrun

Reputation: 886948

We can use sapply in base R

df[-1] <- +(sapply(c(2, 3), `==`, df$cue))

Upvotes: 1

TarJae
TarJae

Reputation: 78917

  
  df %>% 
  mutate(C2 = case_when(cue == 2 ~ 1
                        TRUE ~ 0),
         C3 = case_when(cue ==3 ~ 1,
                        TRUE ~ 0))

Upvotes: 3

Elia
Elia

Reputation: 2584

A super easy base solution

df <- data.frame(cue=sample(c(1:3),10,replace = T),c2=sample(c(0,1),10,replace = T),c3=sample(c(0,1),10,replace = T))

df$c2 <- ifelse(df$cue==2,1,0)
df$c3 <- ifelse(df$cue==3,1,0)

EDIT

to add another dplyr solution

df <- dplyr::mutate(df,c2= ifelse(cue==2,1,0),c3= ifelse(cue==3,1,0))

Upvotes: 1

Related Questions