如何遍历列表

时间:2018-06-29 11:33:24

标签: r

我想遍历列表列表(在数据框中),以便为每个活检部位添加一个随机数,除了活检部位:无,在这种情况下不会粘贴

输入:

list(c("Biopsy site: Duodenal bulb", "Biopsy site: Stomach", 
"Biopsy site: None", "Biopsy site: D2 - 2nd part of duodenum"
), "Biopsy site: None", c("Biopsy site: D2 - 2nd part of duodenum", 
"Biopsy site: Stomach", "Biopsy site: Oesophagus"), c("Biopsy site: Stomach", 
"Biopsy site: None", "Biopsy site: Oesophagus"), c("Biopsy site: Duodenal bulb", 
"Biopsy site: Stomach"))

预期输出

[1] "3 Biopsy site: Duodenal bulb"             "5 Biopsy site: Stomach"                   "Biopsy site: None"                      "7 Biopsy site: D2 - 2nd part of duodenum"

[[2]]
[1] "Biopsy site: None"

[[3]]
[1] "8 Biopsy site: D2 - 2nd part of duodenum" "3 Biopsy site: Stomach"                   "7 Biopsy site: Oesophagus"               

[[4]]
[1] "6 Biopsy site: Stomach"    "Biopsy site: None"       "3 Biopsy site: Oesophagus"

[[5]]
[1] "2 Biopsy site: Duodenal bulb" "3 Biopsy site: Stomach"      

尝试

    lapply(OGDProcedureDf$BiopsyType, function(p)
ifelse(!grepl("None",OGDProcedureDf$BiopsyType),paste(sample(1:10),OGDProcedureDf$BiopsyType),"")
        )

但是我认为问题在于这是一个嵌套列表,因此我需要嵌套lapply吗?

1 个答案:

答案 0 :(得分:1)

不需要嵌套的lapply,实际上您的尝试非常接近:

lst_0 <- list(c("Biopsy site: Duodenal bulb", "Biopsy site: Stomach", 
"Biopsy site: None", "Biopsy site: D2 - 2nd part of duodenum"
), "Biopsy site: None", c("Biopsy site: D2 - 2nd part of duodenum", 
"Biopsy site: Stomach", "Biopsy site: Oesophagus"), c("Biopsy site: Stomach", 
"Biopsy site: None", "Biopsy site: Oesophagus"), c("Biopsy site: Duodenal bulb", 
"Biopsy site: Stomach"))

lapply(lst_0, function(p)
  ifelse(!grepl("None",p),paste(sample(1:10),p),p)
)