我有一個包含 6 個資料框的串列,它們都包含相同的列名。我想根據與另一列中的變數匹配的列名(讓我們稱之為“索引”)對所有 6 個資料框進行子集化,但我遇到了困難。
示例:串列中的 2 個資料幀(注意 - 每個資料幀的索引相同,因此每個資料幀只需選擇相同的列):
[[0]]
a_1 b_1 c_1 a_2 b_2 c_2 Index
3 red no 2 yellow yes 1
[[1]]
a_1 b_1 c_1 a_2 b_2 c_2 Index
3 red no 2 yellow yes 2
我想要的輸出
[[0]]
a_1 b_1 c_1 Index
3 red no 1
[[1]]
a_2 b_2 c_2 Index
2 yellow yes 2
我試過代碼
newlist<-lapply(samplelist,function(x) dplyr::select(ends_with(Index)))
這會生成錯誤“is_character(match) 中的錯誤:找不到物件‘索引’”。我不確定如何最好地使此代碼正常作業,還是應該嘗試完全不同的方法?
更新:
dput(samplelist)
`1` = structure(list(ID = 12345, Com = structure(8296, class = "Date"),
NCom = structure(8533, class = "Date"),
a_1 = "Yes", b_1 = 160, c_1 = 160, d_1 = "No",
e_1 = 0, f_1 = "No", g_1 = 0, h_1 = "Yes",
a_2 = "Yes", b_2 = 155, c_2 = 155, d_2 = "No",
e_2 = 0, d_2 = "No", e_2 = 0, f_2 = "Yes",
Index = "1", Index_date = structure(9265, class = "Date")), row.names = 1L, class = "data.frame"))
`2` = structure(list(Patient_ID = 22222, Com = structure(8296, class = "Date"),
NCom = structure(8533, class = "Date"),
a_1 = "Yes", b_1 = 160, c_1 = 160, d_1 = "No",
e_1 = 0, f_1 = "No", g_1 = 0, h_1 = "Yes",
a_2 = "Yes", b_2 = 155, c_2 = 155, d_2 = "No",
e_2 = 0, d_2 = "No", e_2 = 0, f_2 = "Yes",
Index = "2", Index_date = structure(8835, class = "Date")), row.names = 2L, class = "data.frame"))
uj5u.com熱心網友回復:
我認為您很接近,請嘗試:
lapply(samplelist, function(x) select(x, ends_with(x[["Index"]])))
$`1`
a_1 b_1 c_1 d_1 e_1 f_1 g_1 h_1
1 Yes 160 160 No 0 No 0 Yes
$`2`
a_2 b_2 c_2 d_2 e_2
2 Yes 155 155 No 0
資料
samplelist <- list(
`1` = structure(list(ID = 12345, Com = structure(8296, class = "Date"),
NCom = structure(8533, class = "Date"),
a_1 = "Yes", b_1 = 160, c_1 = 160, d_1 = "No",
e_1 = 0, f_1 = "No", g_1 = 0, h_1 = "Yes",
a_2 = "Yes", b_2 = 155, c_2 = 155, d_2 = "No",
e_2 = 0,
Index = "1", Index_date = structure(9265, class = "Date")), row.names = 1L, class = "data.frame"),
`2` = structure(list(Patient_ID = 22222, Com = structure(8296, class = "Date"),
NCom = structure(8533, class = "Date"),
a_1 = "Yes", b_1 = 160, c_1 = 160, d_1 = "No",
e_1 = 0, f_1 = "No", g_1 = 0, h_1 = "Yes",
a_2 = "Yes", b_2 = 155, c_2 = 155, d_2 = "No",
e_2 = 0,
Index = "2", Index_date = structure(8835, class = "Date")), row.names = 2L, class = "data.frame"))
uj5u.com熱心網友回復:
這是一個選項。您的資料有重復的列名,所以我只選擇其中一個重復項。
library(tidyverse)
samplelist |>
map(\(x){
x <- tibble(x, .name_repair = make.unique)
var <- pull(x, Index)
select(x, ends_with(glue::glue("_{var}")), Index)
})
#> $`1`
#> # A tibble: 1 x 9
#> a_1 b_1 c_1 d_1 e_1 f_1 g_1 h_1 Index
#> <chr> <dbl> <dbl> <chr> <dbl> <chr> <dbl> <chr> <chr>
#> 1 Yes 160 160 No 0 No 0 Yes 1
#>
#> $`2`
#> # A tibble: 1 x 7
#> a_2 b_2 c_2 d_2 e_2 f_2 Index
#> <chr> <dbl> <dbl> <chr> <dbl> <chr> <chr>
#> 1 Yes 155 155 No 0 Yes 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/522767.html
標籤:r列表
上一篇:繪制多列的均值
