[英]R loop to apply same function to multiple dataframes
我有多個數據框,我需要在其中應用相同的功能(唯一)
df1 = data.frame(Bird_ID = c(1:6,7,7,6,2,1))
df2 = data.frame(Bird_ID = c(1:10,7,7,6,2,1,10,9,3))
在每個 df 我想應用以下函數來向我顯示唯一的個人列表:
individuals1 = data.frame(length(unique(df1[,1])))
individuals2 = data.frame(length(unique(df2[,1])))
這里我們有7 個和10 個唯一 ID。 這很容易,但問題是有時我有不止 2 個 df。 如何將唯一函數應用於所有數據幀並具有1 個輸出數據幀,它為我提供每個 df 的唯一個體數量,如下所示:
output = data.frame(Index = c("Unique.ID"), df1 = c(7),df2=c(10))
#index df1 df2
#Unique.ID 7 10
有很多方法可以實現這一目標。 這是使用dplyr
包中的函數的一種方法
library("dplyr")
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
df1 = data.frame(Bird_ID = c(1:6,7,7,6,2,1))
df2 = data.frame(Bird_ID = c(1:10,7,7,6,2,1,10,9,3))
# combine the dataframes into a named list, for convenience
df_list <- list(df1 = df1, df2 = df2)
# bind, group, and summarise
bind_rows(df_list, .id = "df_name") %>%
group_by(df_name) %>%
summarise(n_unique = length(unique(Bird_ID)))
#> # A tibble: 2 × 2
#> df_name n_unique
#> <chr> <int>
#> 1 df1 7
#> 2 df2 10
由reprex 包(v2.0.1) 於 2021 年 10 月 26 日創建
df1 = data.frame(Bird_ID = c(1:6,7,7,6,2,1))
df2 = data.frame(Bird_ID = c(1:10,7,7,6,2,1,10,9,3))
l <- mget(x = ls(pattern = "df"))
library(tidyverse)
map_df(l, ~n_distinct(.x[[1]]))
#> # A tibble: 1 x 2
#> df1 df2
#> <int> <int>
#> 1 7 10
由reprex 包(v2.0.1) 於 2021 年 10 月 26 日創建
根據
sapply(l, function(x) length(unique(x[[1]])))
df1 df2
7 10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.