'Loop that calculates phylogenetic signal for each column of a trait data frame

I am trying to understand the phylogenetic signal of my functional traits, therefore calculate it. Because of the size of the data frame, I was thinking of creating a loop. I want the loop to run through each column of data_df.

The basic function runs like this:

library(picante)

trait_1 <- trait_df[,1]
names(trait_1) <- rownames(trait_df)
physig_1 <- phylosig(phylo_tree, setNames(trait_1, rownames(trait_1)), method = "lambda", test = T, nsim=99)
r


Solution 1:[1]

This is how to calculate the K-statistic and the p value of the phylogenetic signal for every column of taxa metadata table mammal.data considering the tree mammal.tree:

library(tidyverse)
library(phytools)
#> Loading required package: ape
#> Loading required package: maps
#> 
#> Attaching package: 'maps'
#> The following object is masked from 'package:purrr':
#> 
#>     map

data(mammal.tree)
data(mammal.data)

mammal.data %>%
  as.list() %>%
  lapply(function(trait) {
    names(trait) <- rownames(mammal.data)
    res <- phylosig(mammal.tree, trait, test=TRUE)
    
    list(
      P = res$P,
      K = res$K
    )
  }) %>%
  enframe() %>%
  unnest_auto(value)
#> Using `unnest_wider(value)`; elements have 2 names in common
#> # A tibble: 2 × 3
#>   name          P     K
#>   <chr>     <dbl> <dbl>
#> 1 bodyMass  0.001 0.800
#> 2 homeRange 0.551 0.115

This procedure can also be adapted to the lambda method, which output different numbers:

library(tidyverse)
library(phytools)
#> Loading required package: ape
#> Loading required package: maps
#> 
#> Attaching package: 'maps'
#> The following object is masked from 'package:purrr':
#> 
#>     map

data(mammal.tree)
data(mammal.data)

mammal.data %>%
  as.list() %>%
  lapply(function(trait) {
    names(trait) <- rownames(mammal.data)
    res <- phylosig(mammal.tree, trait, method = "lambda", test=TRUE)
    
    list(
      lambda = res$lambda,
      logL = res$logL,
      logL0 = res$logL0,
      P = res$P
    )
  }) %>%
  enframe() %>%
  unnest_auto(value)
#> Using `unnest_wider(value)`; elements have 4 names in common
#> # A tibble: 2 × 5
#>   name      lambda  logL logL0        P
#>   <chr>      <dbl> <dbl> <dbl>    <dbl>
#> 1 bodyMass  1.01   -332. -359. 1.74e-13
#> 2 homeRange 0.0554 -270. -270. 6.00e- 1

Created on 2022-05-04 by the reprex package (v2.0.0)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1