[英]How can I design an r function that selects specific elements from a list of lists, and returns a dataframe as an output
我正在嘗試建立一個r函數,該函數將從列表中選擇相關元素,並最終以數據幀作為輸出。
這是我正在使用的列表:
test_list<-list(set1=list(2, NA, NA, 8, NA, NA, 2), set2=list(4, 6, NA, NA, 2, 1, 1), set3=c(2, 3, 2, 1, NA, NA, NA))
對於列表中的每個元素,我只想保留包含少於4個NA元素的子列表。
這是我構建的功能:
is.useful <-function(x){ #x is a list of sublists
#I want to keep only the sublists with less than 4 NA elements
vector <-c()
for(i in x){
if(sum(is.na(x[[i]])) <= 3){
vector <-c(vector, unlist(x[[i]]))
}
}
return (vector)
}
正在運行is.useful(test_list)
,我在x [[i]]中遇到錯誤:輸入“ list”
我在這里不了解這個問題,因為: sum(is.na(test_list[["set1"]]))
返回正確答案4, unlist(test_list[["set1"]])
也給我該子列表vector( is.vector(unlist(test_list[["set1"]]))
返回TRUE)
我還嘗試了其他方法,即使用以下命令將列表列表轉換為數據框:
dd <- as.data.frame(matrix(unlist(test_list), nrow=length(unlist(test_list[1]))))
從那里,我嘗試運行一個非常相似的函數,但不取消列表:
is.useful2 <-function(x){ #x is dataframe
#I want to keep only the vectors with less than 4 NA elements
vector <-c()
for(i in x){
if(sum(is.na(x[i])) <= 3){
vector <-c(vector, (x[i]))
}
}
return (vector)
}
is.useful2(dd)
在[.data.frame
(x,i is.useful2(dd)
返回錯誤:選擇了未定義的列
我期望什么? 在此特定示例中,我希望有2個向量set2和set3的數據幀,其中我的NA值小於4。
我有點迷路了。 我做錯了什么 ?
非常感謝你的幫助。
希望這可以幫助:
do.call(cbind,test_list[sapply(test_list,function(x)sum(is.na(unlist(x))))<4])
set2 set3
[1,] 4 2
[2,] 6 3
[3,] NA 2
[4,] NA 1
[5,] 2 NA
[6,] 1 NA
[7,] 1 NA
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.