简体   繁体   English

我如何使用 dplyr 跨所有列计算 function,但所有其他列没有 NA 和没有 0?

[英]How i can calculate a function across all columns with one column but all the other column that have no NA and no 0, using dplyr?

i have a data frame that looks like this:我有一个看起来像这样的数据框:

A一个 B C C D D
1 1 0 0 2.1 2.1 6.2 6.2
2 2 3.2 3.2 3.2 3.2 0 0
3 3 4.4 4.4 NA不适用 8.3 8.3
4 4 NA不适用 0 0 0 0
5 5 NA不适用 NA不适用 8.8 8.8
6 6 NA不适用 NA不适用 0 0
7 7 30 30 0 0 9.1 9.1
8 8 30 30 6.6 6.6 0 0

I want to calculate the pariwise sum of A with all the columns (including itself) but only those who match the A but are NOT NA and NOT 0.我想用所有列(包括它自己)计算 A 的按位总和,但只有那些与 A 匹配但不是 NA 且不是 0 的列。

The ideal output must be:理想的 output 必须是:

A一个 B C C D D
72 72 12.6 12.6 22.9 22.9 68.4 68.4
library(tidyverse)
A = seq(1:8)
B = c(0,3.2,4.4,NA,NA,NA,NA,NA)
C = c(2.1,3.2,NA,0,NA,NA,0,6.6)
D = c(6.2,0,8.3,0,8.8,0,9.1,0)
table = tibble(A,B,C,D);table

My effort is:我的努力是:

table%>%
  dplyr::filter(!is.na(A))%>%
  dplyr::summarise(across(everything(), ~ sum(.x,A),na.rm=TRUE))

How i can do this in R using dplyr?我如何使用 dplyr 在 R 中做到这一点? Any help?有什么帮助吗?

  1. base
sapply(table, \(x) sum((x + table$A)[!is.na(x) & x != 0]))
  1. dplyr
table %>%
  summarise(across(everything(), ~ sum((.x + A)[!is.na(.x) & .x != 0])))

# # A tibble: 1 × 4
#       A     B     C     D
#   <int> <dbl> <dbl> <dbl>
# 1    72  12.6  22.9  48.4

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

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