【问题标题】:Select a group of columns, evaluate each cell, create new variable based on evaluation, append to dataset using dplyr [duplicate]选择一组列,评估每个单元格,根据评估创建新变量,使用 dplyr 附加到数据集 [重复]
【发布时间】:2015-06-19 17:51:18
【问题描述】:

我有一个数据框,我想从中选择几列,然后逐行检查所有这些列是否大于 3。这部分正在工作。

然后我想创建一个 1/0 标志来表示此条件为真,然后将其添加回 FULL 数据集。我可以用 dplyr 做所有事情,直到我不得不求助于 cbind() 来添加新变量。有没有 dpylr 方法可以做到这一点?

代码如下:

vars=as.character(paste("sect4q",letters[c(1,4,5,6:16)],sep=""))

fsurv=structure(list(surveyid = 41:44, ID = c(90002, 90078, 90097, 
90120), sect4qa = c(4, 5, 4, 4), sect4qb = c(4, 5, 3, 5), sect4qc = c(4, 
5, 3, 5), sect4qd = c(4, 5, 5, 5), sect4qe = c(4, 5, 3, 5), sect4qf = c(4, 
5, 4, 4), sect4qg = c(5, 5, 5, 5), sect4qh = c(2, 4, 4, 4), sect4qi = c(4, 
4, 4, 4), sect4qj = c(2, 4, 4, 3), sect4qk = c(4, 5, 4, 5), sect4ql = c(4, 
5, 3, 5), sect4qm = c(4, 5, 5, 5), sect4qn = c(4, 5, 4, 5), sect4qo = c(4, 
5, 4, 4), sect4qp = c(4, 5, 4, 5)),.Names = c("surveyid", "ID", "sect4qa", "sect4qb", "sect4qc","sect4qd","sect4qe", "sect4qf", "sect4qg", "sect4qh", "sect4qi", "sect4qj", "sect4qk", "sect4ql", "sect4qm", "sect4qn", "sect4qo", "sect4qp"), class = "data.frame", row.names =c(NA, 4L))

fsurv2= fsurv %>%
select(one_of(vars)) %>%
transmute(fall.flourisher=ifelse(!rowSums(. < 4),1,0))

fsurv=cbind(fsurv,fsurv2)

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我自己找到了 dply 解决方案。下面的代码解决了它:

    fsurv %>%
    mutate(fall.flourisher=ifelse(!rowSums(select(.,one_of(vars)) < 4),1,0))
    

    【讨论】:

      猜你喜欢
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多