2017-07-18 48 views
0

我有一個列表對象,它包含多個列表,每個列表中都有相同的返回對象。下面的列表是這個的簡短版本。子集與關係運算符的列表

logs <- list(list(success = TRUE, details = "check", timestamp = as.Date("2017-10-06")), 
     list(success = FALSE, details = "uncheck", timestamp = as.Date("2017-10-07")), 
     list(success = FALSE, details = "check", timestamp = as.Date("2017-10-08")), 
     list(success = FALSE, details = "uncheck", timestamp = as.Date("2017-10-09"))) 

我想創建兩個矢量:一個矢量(success_true)包含如果所述第一元素的含量等於true每個列表的第二元素的含量,和一個向量(succes_false)包含內容每個列表的第二個元素的第一個元素的內容等於false。我正在尋找的結果如下所示:

success_true <- c("check") 
succes_false <- c("uncheck", "check", "uncheck") 

肖恩威爾金森提出的Sapply解決方案。

# Solution number 1 by Shaun Wilkinson: sapply 
successes <- sapply(logs, function(e) e$success) 
details <- sapply(logs, function(e) e$details) 
success_true <- details[successes] 
success_false <- details[!successes] 

我也想出了另一種解決方案,它在for循環中包含一個條件語句。

# Solution number 2 by SHW: conditional statement with for loop 
success_true <- c() #create two vectors 
success_false <- c() 

for (log in logs) { 
    if (log$success == TRUE) { 
    success_true <- c(success_true, log$details) #add content of details element to the success_true vector if the condition is met 
    } else { 
    success_false <- c(succes_false, log$details) #add content of details element to the success_false vector if the condition is met 
    } 

回答

0

除了Shauns答案,我已經找到了另一種解決方案是incoorporates條件語句中的for循環。我認爲這個解決方案允許更多的靈活性,因此是我將使用的解決方案。

success_true <- c() #create two vectors 
success_false <- c() 

for (log in logs) { 
    if (log$success == TRUE) { 
    success_true <- c(success_true, log$details) #add content of details element to the success_true vector if the condition is met 
    } else { 
    success_false <- c(succes_false, log$details) #add content of details element to the success_false vector if the condition is met 
    } 
} 
1

試試這個:

successes <- sapply(logs, function(e) e$success) 
details <- sapply(logs, function(e) e$details) 
success_true <- details[successes] 
success_false <- details[!successes] 
+0

此解決方案有效。你可以詳細闡述你在代碼中做什麼? – SHW

+0

當然,這可能不是最優雅的解決方案,但前兩行只是從嵌套列表中提取'success'和'details'元素,並將它們分別強制爲邏輯向量和字符向量。第二部分只是「細節」向量的邏輯子集。 –