【问题标题】:Two Column R Dataframe to Named LIst [duplicate]两列 R 数据框到命名列表 [重复]
【发布时间】:2020-11-11 23:25:58
【问题描述】:

我正在尝试将两列数据框转换为命名列表。 StackOverflow 上有几种解决方案,其中第一列中的每个值都成为“名称”,但我希望将第 2 列中的值折叠为第 1 列中的常见值。

例如,列表应如下所示:

# Create a Named list of keywords associated with each file. 
fileKeywords <- list(fooBar.R = c("A","B","C"),
                 driver.R = c("A","F","G"))

我可以使用以下方法检索“fooBar.R”的所有关键字:

# Get the keywords for a named file
fileKeywords[["fooBar.R"]]

我的数据框看起来像:

df <- read.table(header = TRUE, text = "
file        keyWord
'fooBar.R'  'A'
'fooBar.R'  'B'
'fooBar.R'  'C'
'driver.R'  'A'
'driver.R'  'F'
'driver.R'  'G'
")

我确定我缺少一个简单的解决方案。

【问题讨论】:

  • split(df$keyWord, df$file)

标签: r list dataframe


【解决方案1】:

你可以使用unstack:

as.list(unstack(rev(df)))

$driver.R
[1] "A" "F" "G"

$fooBar.R
[1] "A" "B" "C"

这相当于as.list(unstack(df, keyWord~file))

【讨论】:

    【解决方案2】:

    我们可以在base R中使用stack

    stack(fileKeywords)[2:1]
    

    如果是相反的,那我们可以做

    with(df, tapply(keyWord, file, FUN = I))
    

    -输出

    #$driver.R
    #[1] "A" "F" "G"
    
    #$fooBar.R
    #[1] "A" "B" "C"
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 2020-05-22
      • 1970-01-01
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      • 2017-12-28
      相关资源
      最近更新 更多