簡體   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