[英]Apply a function to each row of a matrix without using lapply function in R
[英]Using lapply to apply function to each row in a tibble
这是我的代码尝试将函数应用于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
应该为每个元素应用一个函数?
invisible
用于避免显示输出。 此外,您必须循环遍历名为“value”的列的元素,而不是整个列。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.