r - 从 R 中的列表创建数据框

标签 r dataframe

我有一个 list Path我想从中创建一个 dataframe具有以下特征:2 列,numberuri行数与我的 Path 中的位置一样多列表。

> Path
[[1]]
[1] S1A_IW_GRDH_1SDV_20190818T175529_20190818T175554_028627_033D25_22ED.SAFE

[[2]]
[1] S2A_MSIL1C_20190823T061631_N0208_R034_T42TXS_20190823T081730.SAFE

为此,我开始使用此代码。

df <- data.frame(number = c(1:length(Path)),
                 uri = c(Path[[1]], Path[[2]]))

number列已链接到 Path 的维度使用 1:length(Path) 列出,但是,我如何填充 uri列相应。意思是,Path[[1]]的值应该在 row 1 , column uri ,依此类推,以防万一 Path有更多的值(value)吗?

-- 编辑--

我需要将第三列添加到 dataframe哪些内容应取决于 Path[[i]] 的值。第三列名为 plugin

  • 如果 Path开始于S1pluging的值该行应该是 "class org.esa.s1tbx.io.sentinel1.Sentinel1ProductReaderPlugIn"

  • 如果 Path开始于S2pluging的值该行应该是 "class org.esa.s2tbx.dataio.s2.ortho.plugins.Sentinel2L1CProduct_Multi_UTM42N_ReaderPlugIn"

为此,我想使用 grepl('S2', Path)代码来检查条件,但我不确定如何在 dataframe 中分配适当的值

最佳答案

一个选项是来自base Rstack,用于在命名列表后创建两列data.frame > 带有序列的向量

stack(setNames(Path, seq_along(Path)))[2:1]

或者另一种选择是取消列出 list 并创建 data.frame (假设 list 元素长度 1)

data.frame(number = seq_along(Path), url = unlist(Path))

如果list的元素的长度不相等

data.frame(number = rep(seq_along(Path), lengths(Path)), url = unlist(Path))

或者我们可以使用tibble中的enframe

library(tibble)
library(tidyr)
library(purrr)   
library(dplyr) 
enframe(Path, name = "number", value = "url") %>%
      unnest %>%
      mutate(Plugin = case_when(substr(url, 1, 2) == "S1" ~ "class org.esa.s1tbx.io.sentinel1.Sentinel1ProductReaderPlugIn", TRUE ~ "class org.esa.s2tbx.dataio.s2.ortho.plugins.Sentinel2L1CProduct_Multi_UTM42N_ReaderPlugIn"))

关于r - 从 R 中的列表创建数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57628178/

相关文章:

Python二维列表到数据框列

r - dplyr 替换多个变量中的值

r - 如何从R中的日期中减去月份?

r - 将中值添加到每个框(不是 ggplot)

r - DT [!(x ==。)]和DT [x!=。]不一致地对待x中的NA

Python:在另一个数据框中的其他两列之间查找值

r - ggplot2 中的圆形直方图,条形间距均匀且没有多余线条

r - 使用 R 将连续时间序列数据转换为每日每小时表示

r - Excel 日期格式未正确导入到 R 中

python - Pandas Dataframe 中的列和行的迭代