【问题标题】:R find index of a variable and subset a lsitR找到一个变量的索引和一个列表的子集
【发布时间】:2022-11-30 23:33:41
【问题描述】:

我有一个看起来像这样的列表

#Make dataframes
df1 = data.frame(x = c("a", "b", "c"), y = 1:3, stringsAsFactors = F)
df2 = df1 %>% mutate(y = y*2)
df3 = df1 %>% mutate(y = y*3)

#Make a name for each dataframe
myvar = "fname"

#Combine name and dataframe into a list
mylist = list(myvar, df1)

#Add the other dataframes and name to the list (done in a loop for my bigger dataset
list2 = list(myvar, df2)
mylist = rbind(mylist, list2)

list3  = list(myvar, df3)
mylist = rbind(mylist, list3)

我想提取列表的一个子集,其中包含与“c”相关的所有数据

  x y
3 c 3
  x y
3 c 6
  x y
3 c 9

这是我尝试过的方法,但它不起作用

#Find all instances of "c"
picksite = "c"

site_indices = which(mylist[,2] == picksite)
mylist[site_indices,]

关于如何执行此操作的任何建议,甚至是更好地理解列表的链接?非常感谢。

【问题讨论】:

    标签: r list


    【解决方案1】:

    我认为包装 lapply 的 which 可以解决这个问题:

    lapply(mylist[,2], FUN = function(i) which(i == "c"))
    #$mylist
    #[1] 3
    #
    #$list2
    #[1] 3
    #
    #$list3
    #[1] 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      相关资源
      最近更新 更多