我有一个获取单元格值并从中生成注释的函数。
我正在努力学习如何有效地使用申请。
我传入一个包含10行和4列的数据框,目的是根据行的每个单元格中包含的值为每行创建一个句子
report <- iris
build_comments <- function (report) {
mydf <- report
mycomment <- paste("Analysis Of", mydf[,5],"for flower", mydf[,5], "with width", mydf[,2], "being the most impacted with ",
"Most of the items had length of", mydf[,1],
sep = " ")
cat(mycomment)
}
apply(report[,c(2,3,10,11)],1,build_comments)
不幸的是,它正在构建一个评论,其中列中的每个项目都添加到占位符。任何人都可以看到错误
如果您觉得这样做更容易,我也会采用purrr
方式。
答案 0 :(得分:1)
试试这个例子:
mtcars$comment <-
with(mtcars,
paste("This car has", cyl, "cylinders",
"and", gear, "gears."))
或者正如罗兰建议的那样,使用sprintf()
:
mtcars$comment <-
with(mtcars,
sprintf("This car has %i cylinders and %i gears.",
cyl, gear))
with()
只是评估data.frame中的表达式,避免重复输入mtcars$
。
# without using "with()"
mtcars$comment <-
sprintf("This car has %i cylinders and %i gears.",
mtcars$cyl, mtcars$gear)