我正在尝试使用sprintf
在一个句子中打印出整数和字符串变量。
请参见下面的代码:
sprintf("Candidate %s got %i laughs and %i applauses", final[[m]][1], laugh(final[[m]][2])), applause(final[[m]][2]))
您能检查我是否以正确的方式使用列表索引吗?
还有其他简洁的方法吗?
答案 0 :(得分:1)
您应将%i
更改为%d
以打印整数值。另外,请检查[]
的子集操作[[]]
与list
运算符。请参见下面的代码:
library(randomNames)
# data simulation
set.seed(123)
n <- 10
df <- data.frame(
names = randomNames(n, which.names="first"),
applause <- sample(10, n, replace = TRUE),
laugh <- sample(10, n, replace = TRUE)
)
applause <- function(x) {
as.integer(x[[1]])
}
laugh <- function(x) {
as.integer(x[[2]])
}
final <- apply(df, 1, function(x) list(x[1], list(x[2],x[3])))
# printing of data
for(m in seq_along(final)) {
print(sprintf("Candidate %s got %d laughs and %d applauses", final[[m]][[1]], laugh(final[[m]][[2]]) , applause(final[[m]][[2]])))
}
输出:
[1] "Candidate Raafi got 2 laughs and 10 applauses"
[1] "Candidate Ja' Drianna got 5 laughs and 10 applauses"
[1] "Candidate Reilly got 5 laughs and 7 applauses"
[1] "Candidate Cristol got 4 laughs and 8 applauses"
[1] "Candidate Shawnna got 2 laughs and 1 applauses"
[1] "Candidate Nabeel got 2 laughs and 5 applauses"
[1] "Candidate Katrina got 3 laughs and 8 applauses"
[1] "Candidate Shania got 5 laughs and 3 applauses"
[1] "Candidate Zoe got 3 laughs and 4 applauses"
[1] "Candidate Zufar got 9 laughs and 3 applauses"