繁体   English   中英

对于 R,按行求和在 dplyr 中不起作用

[英]Rowwise sum is not working in dplyr for R

数据集

我已经为我的问题模拟了这个数据集:

#### Set Seed ####
set.seed(123)

#### Create Data Frame ####
df <- data.frame(x1 = rbinom(n=100,
                              size=1,
                              prob = .5),
                 x2 = rbinom(n=100,
                              size=1,
                              prob = .5),
                 x3 = rbinom(n=100,
                              size=1,
                              prob = .5))

#### Convert to Tibble ####
tibble <- df %>% 
  as_tibble()

问题

当我运行 X 值的rowwise汇总时:

#### Summarize Rowwise Values ####
tibble %>% 
  rowwise() %>% 
  mutate(Sum.X = sum(.,
                     na.rm = T))

我得到了这个摘要,这不是我想要的。 这似乎是对其他事情的总结:

# A tibble: 100 × 4
# Rowwise: 
      x1    x2    x3 Sum.X
   <int> <int> <int> <int>
 1     0     1     0   145
 2     1     0     1   145
 3     0     0     1   145
 4     1     1     1   145
 5     1     0     0   145
 6     0     1     1   145
 7     1     1     0   145
 8     1     1     0   145
 9     1     0     0   145
10     0     0     0   145
# … with 90 more rows

但是,我正在按行查找如下所示的摘要:

# A tibble: 100 × 4
# Rowwise: 
      x1    x2    x3 Sum.X
   <int> <int> <int> <int>
 1     0     1     0     1
 2     1     0     1     2
 3     0     0     1     1
 4     1     1     1     3
 5     1     0     0     1
 6     0     1     1     2
 7     1     1     0     2
 8     1     1     0     2
 9     1     0     0     2
10     0     0     0     0
# … with 90 more rows

您不需要使用rowwise ,只需使用rowSums

tibble %>% 
  mutate(Sum.X = rowSums(., na.rm = T))
# # A tibble: 100 × 4
#       x1    x2    x3 Sum.X
#    <int> <int> <int> <dbl>
#  1     0     1     0     1
#  2     1     0     1     2
#  3     0     0     1     1
#  4     1     1     1     3
#  5     1     0     0     1
#  6     0     1     1     2
#  7     1     1     0     2
#  8     1     1     0     2
#  9     1     0     0     1
# 10     0     0     0     0
# # … with 90 more rows
# # ℹ Use `print(n = ...)` to see more rows

使用 c_across:

df %>% 
  rowwise() %>% 
  mutate(Sum.X = sum(c_across(everything()),na.rm = T))
# A tibble: 100 × 4
# Rowwise: 
      x1    x2    x3 Sum.X
   <int> <int> <int> <int>
 1     1     0     1     2
 2     0     1     0     1
 3     0     0     0     0
 4     1     1     0     2
 5     1     0     1     2
 6     0     1     1     2
 7     0     0     0     0
 8     1     0     1     2
 9     1     1     0     2
10     0     0     0     0
# … with 90 more rows
# ℹ Use `print(n = ...)` to see more rows

也可以使用基数 R:

apply(df, 1, sum, na.rm = T)
  [1] 2 1 0 2 2 2 0 2 2 0 2 2 1 2 1 1 2 2 2 1 2 1 0 3 2 3 0 2 1 2 2 3 2 2 2 1 2 3 2 0 2 2 2 1 2 1 2 1 2
 [50] 1 3 1 1 2 1 2 2 2 2 1 3 1 1 1 1 3 1 2 2 2 1 3 1 1 1 0 3 3 1 1 2 1 2 0 3 2 2 3 2 2 2 2 3 2 2 3 2 2
 [99] 1 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM