【问题标题】:Update row values based on condition in R根据 R 中的条件更新行值
【发布时间】:2021-05-02 15:23:17
【问题描述】:

我正在尝试根据条件更新 C2 和 C3 列的值:

• 如果提示类型 = 2,则变量 C2 等于 1, 否则为 0。

• 如果提示类型 = 3,则变量 C3 等于 1, 否则为 0。

数据框图片: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)

谢谢。

【问题讨论】:

  • dput()你的df。

标签: r


【解决方案1】:
  
  df %>% 
  mutate(C2 = case_when(cue == 2 ~ 1
                        TRUE ~ 0),
         C3 = case_when(cue ==3 ~ 1,
                        TRUE ~ 0))

【讨论】:

    【解决方案2】:

    一个超级简单的base 解决方案

    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)
    

    编辑

    添加另一个dplyr 解决方案

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

    【讨论】:

      【解决方案3】:

      我们可以在base R中使用sapply

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-20
        • 2011-11-29
        • 2020-07-08
        • 2021-12-03
        相关资源
        最近更新 更多