【问题标题】:how create new variable form multiple column and row condtion in r如何从 r 中的多列和多行条件创建新变量
【发布时间】:2017-09-20 17:54:36
【问题描述】:

如何在 R 中创建新变量以匹配单个数据框中的多个条件。我想从以下数据集中创建新变量(couple_smokr)。与情侣相关的变量不在数据集中,需要从现有变量中创建(情侣将是那些男性和女性具有相似集群、houseno 和 partnernum 的人)。如果任何人有创建这个 (couple_smoke) 变量的命令,将不胜感激。

View(afgan)
sex    cluster      houseno     partnernum   smoke    **couple_smoke**
male     1            4             2         yes          yes
female   1            4             2         yes          yes
male     1            4             1         no            no
male     3            10            1         no            no
female   3            10            1         yes           no
female   4            4             2          no           no
female   4            4             1          no           no  
male     4            4             3          no           no 

【问题讨论】:

  • 欢迎来到 SO!为了使您的数据可重现,您可以 dput(head(afgan)) 并发布结果吗?
  • 为什么第 4 行和第 5 行中的 malefemale 没有标记 yes

标签: r dataframe


【解决方案1】:

我猜你定义 couple_smoke 当一对夫妇住在同一个家庭并且他们都吸烟时,因此他们也应该对来自 cluster、@987654324 的 smoke 变量有相同的输入@ 和 partnernum。我说的对吗?

那么以下应该可以解决问题:首先输入数据(请按照csgroen指出的方式下次提供dput代码)

afgan <- structure(list(
  sex = structure(c(2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L), 
                  .Label = c("female", "male"), class = "factor"), 
  cluster= c(1, 1, 1, 3, 3, 4, 4, 4), 
  houseno= c(4, 4, 4, 10, 10, 4, 4, 4), 
  partnernum= c(2, 2, 1, 1, 1, 2, 1, 3), 
  smoke = structure(c(1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L), 
    .Label = c("yes", "no"), class = "factor")),
  .Names = c("sex", "cluster", "houseno", "partnernum", "smoke"), 
  row.names = c(NA, 8L), class = "data.frame")

那么,

library(dplyr)
afgan %>% 
  group_by(cluster, houseno, partnernum, smoke) %>% 
  mutate(couple_smoke = ifelse(n() > 1, 1, 0))

dplyr 包的n() 函数计算每组的行数。

【讨论】:

  • 这是完美的。
  • @DharmaN.Bhatta 如果有帮助,请考虑接受这个作为官方答案。谢谢。
【解决方案2】:

考虑基数 R 的 ave(),其中传递一个等于 df 的 nrow() 的 1 向量以求和。

df$couple_smoke <- ifelse(ave(rep(1, nrow(df)), df$cluster, df$houseno,
                          df$partnernum, df$smoke, FUN=sum) > 1, 'yes', 'no')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2022-08-13
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    相关资源
    最近更新 更多