【问题标题】:Getting the name of a specific column of df within a list获取列表中 df 的特定列的名称
【发布时间】:2020-12-04 12:31:46
【问题描述】:

示例数据:

df1 <- as.data.frame(rbind(c(1,2,3), c(1, NA, 4), c(NA, NA, NA), c(4,6,7), c(4, 8, NA)))
df2 <- as.data.frame(rbind(c(1,2,3), c(1, NA, 4), c(4,6,7), c(NA, NA, NA), c(4, 8, NA)))

dfList <- list(df1,df2)
colnames <- c("A","B","C") 

dfList[[1]]

#  V1 V2 V3
# 1  1  2  3
# 2  1 NA  4
# 3 NA NA NA
# 4  4  6  7
# 5  4  8 NA

dfList[[2]]

#  V1 V2 V3
# 1  1  2  3
# 2  1 NA  4
# 3  4  6  7
# 4 NA NA NA
# 5  4  8 NA

# I know I can get the names out like this:

namesvec <- lapply(dfList, function(x) lapply(x, names))

但如果我想得到一个特定的名字,什么都行不通:

names(namesvec[[1]][[1]])
colnames(namesvec[[1]][[1]])
rownames(namesvec[[1]][[1]])
# lapply(county_list, function(x) lapply(x[1], names))
# lapply(county_list, function(x) lapply(x[[1]], names))

这一定很简单,但它让我发疯..

【问题讨论】:

    标签: r list syntax


    【解决方案1】:

    您不使用namesvec &lt;- lapply(dfList, function(x) lapply(x, names)) 来获取列表中的所有名称。使用:

    cols <- lapply(dfList, names)
    cols
    #[[1]]
    #[1] "V1" "V2" "V3"
    
    #[[2]]
    #[1] "V1" "V2" "V3"
    

    现在提取特定的列名使用:

    #First column name of first list
    cols[[1]][1]
    #[1] "V1"
    
    #third column name of first list. 
    cols[[1]][3]
    [1] "V3"
    
    #first column of second list.
    cols[[2]][1]
    [1] "V1"
    

    【讨论】:

    • 谢谢!现在我终于可以停止辱骂我的笔记本电脑了。
    【解决方案2】:

    我们可以使用map

    library(purrr)
    map(dfList, names)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-16
      • 2013-05-15
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 2010-10-05
      • 2012-12-31
      • 2012-08-21
      相关资源
      最近更新 更多