将列合并和求和R

时间:2019-01-15 23:13:19

标签: r dplyr

我有一个关于您的技术问题,请问:

from_date = driver.find_elements_by_id("6A8A7718100001256A44465A5ED3AEAC-fromDate")
from_date = driver.find_element_by_xpath("//input[@id='6A8A7718100001256A44465A5ED3AEAC-fromDate']")
from_date = from_date = driver.find_element_by_css_selector("input[id='6A8A7718100001256A44465A5ED3AEAC-fromDate']")

我想加入并汇总我的列“ f”和“ f2”,并在“ f_news”中重命名

示例:

df <- data.frame(ca = c("a","b","a","c","b", "b"),
                 f = c(3,4,0,NA,3, 4),
                 f2 = c(NA,5,6,1,9, 7),
                 f3 = c(3,0,6,3,0, 8))

您有想法吗(可能是总结,传播,分组依据)

谢谢!

3 个答案:

答案 0 :(得分:3)

使用plyrdplyr,您可以这样做:

df %>% 
  rowwise() %>% 
  mutate(f_new=sum(f, f2, na.rm = T))

# A tibble: 6 x 5
#   ca     f    f2    f3   f_new
#  <fct> <dbl> <dbl> <dbl> <dbl>
#1   a     3    NA     3     3
#2   b     4     5     0     9
#3   a     0     6     6     6
#4   c    NA     1     3     1
#5   b     3     9     0    12
#6   b     4     7     8    11

此方法将保留和NA个值

答案 1 :(得分:2)

以下是使用tidyversedplyr中的tidyr方法的答案

library(tidyverse)

df <- data.frame(ca = c("a","b","a","c","b", "b"),
                 f = c(3,4,0,NA,3, 4),
                 f2 = c(NA,5,6,1,9, 7),
                 f3 = c(3,0,6,3,0, 8))

df %>% 
  replace_na(list(f = 0, f2 = 0)) %>% 
  mutate(f_new = f + f2)
#>   ca f f2 f3 f_new
#> 1  a 3  0  3     3
#> 2  b 4  5  0     9
#> 3  a 0  6  6     6
#> 4  c 0  1  3     1
#> 5  b 3  9  0    12
#> 6  b 4  7  8    11

答案 2 :(得分:2)

Dplyr可以通过以下代码很好地做到这一点。按行可以单独考虑每一行。 mutate命令可对所需的任何列求和。当您有NA并想忽略它们时,na.rm = TRUE会处理该问题。如前所述,如果没有此值,则在任何求和值中都会给出NA。

library(dplyr)
df %>% 
  rowwise() %>% 
  mutate(f_new = sum(f,f2, na.rm = TRUE))