我有一个列表,如:
List_PatientState
[[1]]
BirthYear Hispanic tEye tStatus tKidney
12604 2 0 1 2 2
[[2]]
BirthYear Hispanic tEye tStatus tKidney
9252 2 0 2 1 1
[[3]]
BirthYear Hispanic tEye tStatus tKidney
6613 2 0 1 1 1
[[4]]
BirthYear Hispanic tEye tStatus tKidney
6265 2 0 2 2 1
[[5]]
BirthYear Hispanic tEye tStatus tKidney
6202 2 0 1 1 2
在一个循环中我创建了一个新列表,如果它在我当前的列表列表中可用,我想忽略该列表
有关更多信息,请考虑在我的循环中创建的此列表:
[[6]]
BirthYear Hispanic tEye tStatus tKidney
11773 2 0 1 1 1
这类似于:
List_PatientState[[3]]
我想在我的列表列表中检测到这样的列表,所以,我可以拒绝它添加到我当前的列表列表中。 有人帮我吗? 我将不胜感激。 dput的输出(List_PatientState):
> dput(List_PatientState)
list(structure(list(BirthYear = structure(2L, .Label = c("1",
"2", "3"), class = "factor"), Hispanic = structure(1L, .Label = c("0",
"1"), class = "factor"), tEye = structure(1L, .Label = c("1",
"2"), class = "factor"), tStatus = structure(2L, .Label = c("1",
"2"), class = "factor"), tKidney = structure(2L, .Label = c("1",
"2"), class = "factor")), .Names = c("BirthYear", "Hispanic",
"tEye", "tStatus", "tKidney"), row.names = 12604L, class = "data.frame"),
structure(list(BirthYear = structure(2L, .Label = c("1",
"2", "3"), class = "factor"), Hispanic = structure(1L, .Label = c("0",
"1"), class = "factor"), tEye = structure(2L, .Label = c("1",
"2"), class = "factor"), tStatus = structure(1L, .Label = c("1",
"2"), class = "factor"), tKidney = structure(1L, .Label = c("1",
"2"), class = "factor")), .Names = c("BirthYear", "Hispanic",
"tEye", "tStatus", "tKidney"), row.names = 9252L, class = "data.frame"))
答案 0 :(得分:0)
首先我们创建一些示例数据:
dat <- lapply(1:5,function(x) mtcars[x,]) #List of the first 5 rows of mtcars set
然后,如果你必须使用for loop
:
for (i in 3:6) {
temp <- mtcars[i,]
if(is.na(any(sapply(dat,function(y) all.equal(y,temp)[[1]])))) {
dat[[i]] <- temp
}
}
如果您在循环中创建的data frame
已存在于列表中并且仅添加未列在列表中的data frames
,则基本上会检查每次迭代。
答案 1 :(得分:0)
向量列表
List_PatientState <- list(c(Birthyear=2, Hispanic=0, tEye=1, tStatus=2, tKidney=2),
c(Birthyear=2, Hispanic=0, tEye=2, tStatus=1, tKidney=1),
c(Birthyear=2, Hispanic=0, tEye=1, tStatus=1, tKidney=1),
c(Birthyear=2, Hispanic=0, tEye=2, tStatus=2, tKidney=1),
c(Birthyear=2, Hispanic=0, tEye=1, tStatus=1, tKidney=2))
newv <- list(c(Birthyear=2, Hispanic=0, tEye=1, tStatus=1, tKidney=1)) # duplicate values
newv1 <- list(c(Birthyear=2, Hispanic=0, tEye=2, tStatus=1, tKidney=2)) # unique values
myfun <- function(L, V) {
if (any(sapply(L, function(x) all(V[[1]] == x)))) {
return(L)
} else {
return(c(L,V))
}
}
myfun(List_PatientState, newv) # returns original list
myfun(List_PatientState, newv1) # returns original list + newv1