gpt4 book ai didi

r - 将函数应用于 R 中的数据帧列表

转载 作者:行者123 更新时间:2023-12-01 10:35:37 24 4
gpt4 key购买 nike

我需要有关如何以迭代方式管理列表的帮助。

我有以下列表 list,它由几个具有相同列但行数不同的数据帧组成。示例:

[[1]]
id InpatientDays ERVisits OfficeVisits Narcotics
1 a 0 0 18 1
2 b 1 1 6 1
3 c 0 0 5 3
4 d 0 1 19 0
5 e 8 2 19 3
6 f 2 0 9 2

[[2]]
id InpatientDays ERVisits OfficeVisits Narcotics
7 a 16 1 8 1
8 b 2 0 8 0
9 c 2 1 4 3
10 d 4 2 0 2
11 e 6 5 20 2
12 a 0 0 7 4

我想应用一个函数来获取列表中每个“数据框”的 ID 的所有可能组合。

我打算尝试这样的事情 lapply(list1, function(x) combn(unique(list1[x]$id))) 这当然行不通。喜欢:

[[1]]  
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
[1,] "a" "a" "a" "a" "a" "b" "b" "b" "b" "c" "c" "c" "d" "d" "e"
[2,] "b" "c" "d" "e" "f" "c" "d" "e" "f" "d" "e" "f" "e" "f" "f"

[[2]]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "a" "a" "a" "a" "b" "b" "b" "c" "c" "d"
[2,] "b" "c" "d" "e" "c" "d" "e" "d" "e" "e"

这可能吗?我确信这适用于单个数据帧 df

  combn(unique(df$id),2) 

最佳答案

我们需要使用unique(x$id)

 lapply(list1, function(x) combn(unique(x$id),2))

OP 的代码正在使用 lapply 循环“list1”。匿名函数调用 (function(x)) 返回 list 中的每个“data.frame”,即“x”是“data.frame”。因此,我们只需调用 x$id(或 x[['id']])来提取“id”列。本质上,'x' 不是索引。但是,如果我们需要根据索引进行子集化,我们必须循环遍历“list1”的序列(或者如果 list 元素已命名,则循环遍历 names 的)

lapply(seq_along(list1), function(i) combn(unique(list1[[i]]$id), 2))

关于r - 将函数应用于 R 中的数据帧列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36066336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com