【问题标题】:Using lapply to apply function to each row in a tibble使用 lapply 将函数应用于小标题中的每一行
【发布时间】:2017-11-07 07:08:21
【问题描述】:

这是我的代码,它尝试将函数应用于 tibble 中的每一行,mytib:

> mytib
# A tibble: 3 x 1
  value
  <chr>
1     1
2     2
3     3

这是我的代码,我试图将函数应用于 tibble 中的每一行:

mytib = as_tibble(c("1" , "2" ,"3"))

procLine <- function(f) {
  print('here')
  print(f)
}

lapply(mytib , procLine)

使用lapply

> lapply(mytib , procLine)
[1] "here"
[1] "1" "2" "3"
$value
[1] "1" "2" "3"

此输出表明该函数不是每行调用一次,因为我期望输出是:

here
1
here
2
here
3

如何对 tibble 中的每一行应用函数?

更新:我很欣赏提供的答案,这些答案可以实现我的预期结果,但我在实施中做错了什么? lapply 应该对每个元素应用一个函数?

【问题讨论】:

  • 申请(mytib, 1, procLine) ?
  • 有点棘手.. a=sapply(mytib$value,procLine) 会打印你想要的内容

标签: r


【解决方案1】:

invisible 用于避免显示输出。此外,您必须遍历名为“值”的列的元素,而不是整个列。

invisible( lapply(mytib$value , procLine) )
# [1] "here"
# [1] "1"
# [1] "here"
# [1] "2"
# [1] "here"
# [1] "3"

lapply 默认循环遍历数据框的列。请参见下面的示例。每次迭代都会将两列的值作为一个整体打印出来。

mydf <- data.frame(a = letters[1:3], b = 1:3, stringsAsFactors = FALSE )
invisible(lapply( mydf, print))
# [1] "a" "b" "c"
# [1] 1 2 3

要遍历数据框中列的每个元素,您必须像下面这样循环两次。

invisible(lapply( mydf, function(x) lapply(x, print)))
# [1] "a"
# [1] "b"
# [1] "c"
# [1] 1
# [1] 2
# [1] 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 2019-06-17
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2014-03-16
    相关资源
    最近更新 更多