【问题标题】:Select a column from multiple dataframes in a list从列表中的多个数据框中选择一列
【发布时间】:2016-08-04 13:37:09
【问题描述】:

我的列表有多个数据框,只有两列

DateTime       Value 
30-06-2016      100
31-07-2016      200
.
.
.

我只想从列表中提取列 Value。填充代码对我来说是不成功的。我在这里做错了什么?

actual_data <- lapply(test_data, function(df) df[,is.numeric(df)])
> actual_data[[1]]

data frame with 0 columns and 12 rows

谢谢

【问题讨论】:

  • lapply(test_data, '[', 2)
  • 非常感谢@Sotos。你会解释解决方案吗?
  • 尝试test_data[[1]][1]test_data[[2]][1] 等...你会得到它。提示:看看[ 是如何用于索引的?!
  • test_data[[1]][1] 会给我列表中第一个df的第一列。具体来说,'[' 是做什么的?

标签: r list subset


【解决方案1】:

purrr::map(lapply 的增强版)为此类操作提供了快捷方式:

# Generate test data
set.seed(35156)

test_df   <- data.frame('DateTime' = rnorm(100), 'Value' = rnorm(100))
test_data <- rep(list(test_df), 100)

# Use `map` from the purrr package to subset the data.frames
purrr::map(test_data, 'Value')
purrr::map(test_data, 2)

如您在上面的示例中所见,您可以通过名称、将字符串作为第二个参数传递给purrr::map 或按位置、通过传递数字来选择 data.frame 中的列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 2020-07-04
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多