【问题标题】:Count 30 variables based on condition? [duplicate]根据条件计算 30 个变量? [复制]
【发布时间】:2021-08-23 21:58:17
【问题描述】:

大家好,我是 R 新手,我基本上得到了一个由 31 个变量(ID 和 30 个编码为 1、2、3 的项目)组成的数据框

我想根据特定条件创建一个新变量。我想变成这样:

(因为 2 只出现在这 2 个项目(项目 1 和项目 3)中,所以基本上我想创建一个新变量,显示在这 30 个项目中选择了多少次 2)

非常感谢您的帮助

最好的问候

【问题讨论】:

  • 为什么要从问题中删除代码?

标签: r dplyr tidyverse data-wrangling


【解决方案1】:

感谢 MrFlick:使用 Update1 版本不起作用,因为在 rowSums 中使用 . 会绕过 across()(请参阅评论 MrFlick)

因此,我们可以在 dplyr 工作流程中将rowwise 与c_across 和sum 一起使用:

这是一个例子,ID == 2:

2.更新:

数据:

df <- structure(list(ID = 2L, Item1 = 2L, Item2 = 3L, Item3 = 2L, Item4 = 3L, 
    Newvariable = 2L), class = "data.frame", row.names = c(NA, 
-1L))

代码:

library(dplyr)
df %>% 
    rowwise() %>% 
    mutate(Total = sum(c_across(-ID)==2))

输出:

# Rowwise: 
     ID Item1 Item2 Item3 Item4 Newvariable Total
  <int> <int> <int> <int> <int>       <int> <int>
1     2     2     3     2     3           2     3

更新1: (不起作用)

在rowSums 中使用. 会绕过across()(见评论MrFlick)

df %>% 
    mutate(across(-ID), Total = rowSums(. == 2))

第一个答案:

我们可以使用rowSums:

library(dplyr)
df %>% 
    mutate(Total = rowSums(. == 2))
  ID Item1 Item2 Item3 Item4 Newvariable Total
1  1     2     3     2     3           2     3

【讨论】:

  • 如果它在 ID 列中,它也算 2。可能是不可取的。
  • 你是对的。请看我的更新!
  • 该更新不起作用。试试df &lt;- data.frame(ID=1:2, Item1=c(2,2), Item2=c(1,1))。在 rowSums 中使用 . 会绕过 across()
  • 请看我的更新!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
相关资源
最近更新 更多