字符和整数变量的sprintf输出不正确?

时间:2018-09-21 05:02:35

标签: r printf

我正在尝试使用sprintf在一个句子中打印出整数和字符串变量。 请参见下面的代码:

sprintf("Candidate %s got %i laughs and %i applauses", final[[m]][1], laugh(final[[m]][2])), applause(final[[m]][2]))
  1. 您能检查我是否以正确的方式使用列表索引吗?

  2. 还有其他简洁的方法吗?

1 个答案:

答案 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"