我有一个大数据帧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))
我知道必须有一种方法来迭代这个数据帧。例如,我可以通过df[[2]][[i]]$p.value
访问p.value
,其中i
是行号,但我不知道如何迭代每一行并将此输出保存到列表或新数据帧中。如有任何帮助,我们将不胜感激。
如果我理解您的要求,您就有了一个列表,最简单的方法是使用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
我们还可以将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
另一种可能的解决方案:
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=.)