簡體   English   中英

dplyr通過將摘要函數應用於另一個數據框來計算新列

[英]dplyr calculate a new column by applying summarise function on another dataframe

我想在名為df的數據框中創建一個新列( CNT )。 該值用以下公式計算summarise從功能dplyr包。 它應該返回一個數字,因為我需要在另一個數據幀(= cars )中計數一列,但是過濾條件由df兩列中的值確定。

數據幀:

library(dplyr)
df <- data.frame("my_speed" = 11:20, "my_dist" = c(17,20,15,17,21,23,28,36,50,80))

例如,這是df第一行的計算。

x=df[1,1]
y=df[1,2]

cars %>% 
group_by(speed) %>% 
filter(speed==x & dist==y) %>% 
summarise(count=n()) %>% 
select (count)

我試圖弄清楚如何使用summarise()或其他方法輕松地做到這一點。 注意,如果summarise()返回任何記錄,則應顯示零。

df %>% 
rowwise() %>%
filter(speed==my_spped & dist==my_dist) %>% 
summarise(count=n()) %>% 
select (count) %>% 
mutate(CNT=count)

我們可以定義一個函數

library(tidyverse)

get_count <- function(x, y) {
   cars %>% 
    summarise(count = sum(speed == x & dist == y)) %>% 
    pull(count)
}

並使用map2將其應用於每一行

df %>%
  mutate(CNT = map2(my_speed, my_dist, get_count))


#   my_speed my_dist   CNT
#1        11      17     1
#2        12      20     1
#3        13      15     0
#4        14      17     0
#5        15      21     0
#6        16      23     0
#7        17      28     0
#8        18      36     0
#9        19      50     0
#10       20      80     0

apply相同的基數R等於

get_count <- function(x) {
  nrow(subset(cars, speed == x[1] & dist == x[2]))
}

df$CNT <- apply(df, 1, get_count)

使用rowwise ,我們可以直接獲取邏輯表達式的sum ,而不必執行其他操作

df %>% 
   rowwise %>% 
   mutate(CNT = sum((cars$speed == my_speed) & (cars$dist == my_dist)))
# A tibble: 10 x 3
#   my_speed my_dist   CNT
#      <int>   <dbl> <int>
# 1       11      17     1
# 2       12      20     1
# 3       13      15     0
# 4       14      17     0
# 5       15      21     0
# 6       16      23     0
# 7       17      28     0
# 8       18      36     0
# 9       19      50     0
#10       20      80     0

library(dplyr)

cars %>%
  count(speed, dist) %>%                   # count unique (speed, dist) pairs
  right_join(dat) %>%                      # join to dat, drop all not in dat
  mutate(CNT = coalesce(n, 0L), n = NULL)  # replace NA, create CNT, drop n

數據

dat <- data.frame(
  speed = 11:20,
  dist = c(17, 20, 15, 17, 21, 23, 28, 36, 50, 80)
  )

產量

# A tibble: 10 x 3
   speed  dist   CNT
   <dbl> <dbl> <int>
 1    11    17     1
 2    12    20     1
 3    13    15     0
 4    14    17     0
 5    15    21     0
 6    16    23     0
 7    17    28     0
 8    18    36     0
 9    19    50     0
10    20    80     0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM