Home > Net >  How to convert a list into vector in R
How to convert a list into vector in R

Time:12-06

I have extracted odd_ratios from fisher test as follow. How can i incorporate unlistin the following code. or there is some other solution too.

fisher_or <- apply(ids_df, 1, function(i) tryCatch(fisher.test(table(class.df[,i]))$estimate, error = function(e) NA_real_))

class(fisher_or)
[1] "list"

head(fisher_or)

[[1]]
odds ratio 
 0.2416209 

[[2]]
odds ratio 
 0.8681188 

[[3]]
odds ratio 
         0 

[[4]]
odds ratio 
  3.743399 

[[5]]
odds ratio 
  2.256228 

The issue is i just want to extract numerical values as a list from this. ás my ultimate goal is to bind this with my dataframe and pvalues like this.

edge_table<- cbind(ids_df, fisher_pvalues, fisher_or)

I try following but its not working..

fisher_OR<- do.call(rbind, fisher_or)
edge_table<- cbind(ids_df, fisher_pvalues, fisher_OR)

Note: class(fisher_pvalues)

[1] "numeric"

class(ids_df)
[1] "data.frame"

CodePudding user response:

Assuming I'm understanding what's going on, how about something like this:

library(dplyr)
class.df <- data.frame(
  A = sample(1:2, 100, replace=TRUE), 
  B = sample(1:2, 100, replace=TRUE), 
  C = sample(1:2, 100, replace=TRUE), 
  D = sample(1:2, 100, replace=TRUE)
)

ids_df <- t(combn(names(class.df), 2))
fisher_tests <- apply(ids_df, 1, function(i) tryCatch(fisher.test(table(class.df[,i])), error = function(e) NA_real_))
edge_table <- cbind(ids_df, bind_rows(lapply(fisher_tests, "[", c("p.value", "estimate"))))
edge_table
#>   1 2   p.value  estimate
#> 1 A B 0.2126488 1.7706623
#> 2 A C 1.0000000 0.9267634
#> 3 A D 0.2124925 1.7591799
#> 4 B C 0.5473441 1.3593715
#> 5 B D 0.8427368 0.9082905
#> 6 C D 1.0000000 1.0494569

Created on 2022-12-06 by the reprex package (v2.0.1)

CodePudding user response:

t looks like the fisher_or variable is a list of vectors containing the odds ratios from the Fisher test. To extract the values as a numeric vector, you can use the unlist function.

For example, you could replace this line:

fisher_OR<- do.call(rbind, fisher_or)

with this:

fisher_OR <- unlist(fisher_or)

This will create a numeric vector containing the odds ratios, which you can then use to bind to your data frame.

edge_table <- cbind(ids_df, fisher_pvalues, fisher_OR)

Alternatively, you can use the lapply function to apply unlist to each element of the fisher_or list, and then bind the resulting list directly to your data frame.

fisher_OR <- lapply(fisher_or, unlist)
edge_table <- cbind(ids_df, fisher_pvalues, fisher_OR)
  • Related