我df通過在不同的資料幀上運行單邊 t 檢驗獲得了一個大資料幀:
df <- structure(list(uniqueID = c("101030", "101060"), res = list(structure(list(
statistic = c(t = 19), parameter = c(df = 20),
p.value = 0.00015, conf.int = structure(c(0.389,
Inf), conf.level = 0.95), estimate = c(`mean of x` = 0.412),
null.value = c(mean = 0.22), stderr = 0.01,
alternative = "greater", method = "One Sample t-test", data.name = "mean"), class = "htest"),
structure(list(statistic = c(t = 29), parameter = c(df = 20),
p.value = 4.5e-05, conf.int = structure(c(0.569,
Inf), conf.level = 0.95), estimate = c(`mean of x` = 0.600),
null.value = c(mean = 0.22), stderr = 0.01,
alternative = "greater", method = "One Sample t-test",
data.name = "mean"), class = "htest"))), row.names = c(NA,
-2L), class = c("tbl_df", "tbl", "data.frame"))
我想創建一個新的資料框df_new,我基本上uniqueID取值以及p.value:
df_new <- data.frame(uniqueID = c(101030, '101060'), pval = c(0.00015, 4.5e-05))
我知道必須有一種方法來迭代這個資料框。例如,我可以p.value通過df[[2]][[i]]$p.valuewherei是行號來訪問,但我不知道如何遍歷每一行并將此輸出保存到串列或新資料框。任何幫助將不勝感激。
uj5u.com熱心網友回復:
如果我理解您的要求,那么您有一個串列,最簡單的方法是使用apply函式進行迭代:
df_new <- data.frame(
uniqueID = df$uniqueID,
pval = sapply(df$res, function(x) x[["p.value"]])
)
輸出:
r$> df_new
uniqueID pval
1 101030 1.5e-04
2 101060 4.5e-05
uj5u.com熱心網友回復:
我們還可以hoist將p.value列向上嵌套一層:
library(tidyr)
library(dplyr)
hoist(df, .col = res, "p.value") %>%
select(uniqueID, p.value)
#> # A tibble: 2 × 2
#> uniqueID p.value
#> <chr> <dbl>
#> 1 101030 0.00015
#> 2 101060 0.000045
uj5u.com熱心網友回復:
另一種可能的解決方案:
library(tidyverse)
df %>%
rowwise %>%
mutate(pvalue = res %>% flatten %>% .["p.value"] %>% unlist, res = NULL)
#> # A tibble: 2 × 2
#> # Rowwise:
#> uniqueID pvalue
#> <chr> <dbl>
#> 1 101030 0.00015
#> 2 101060 0.000045
或使用purrr:
map_dbl(df$res, ~ .x$p.value) %>% bind_cols(uniqueID = df[,1], pvalue=.)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/414683.html
標籤:
