我一直在努力(作为初学者)做到这一点。我有一个文本,希望将某些部分替换为数据框的行条目(如果更容易,也可以使用矩阵)。我有一个示例数据集,如下所示:
x y z
1 5 apple green
2 7 banana yellow
3 13 mango red
我被困在这里:
for (x in mydata[["x"]]) {
for (y in mydata[["y"]]) {
for (z in mydata[["z"]]) {
print(paste("The year is", x, y,"color", z))
}
}
}
但是,这将使用所有可能的组合来呈现文本。我想得到:
"The year is 5 apple color green"
"The year is 7 banana color yellow"
"The year is 13 mango color red"
我尝试过重复,如果有一段时间,但我得到的是第一个,最后一个或全部组合返回。如何定义每行只需要一个句子?
谢谢你的帮助。
我们不需要paste
向量化的循环。
paste("This year is", df1$x, df1$y, "color", df1$z)
或使用 sprintf
sprintf("This year is %s %s color %s", df1$x, df1$y, df1$z)
或不打3次``df1''
do.call(sprintf, c(df1, fmt = "This year is %s %s color %s"))
#[1] "This year is 5 apple color green" "This year is 7 banana color yellow"
#[3] "This year is 13 mango color red"
OP的帖子使用了嵌套for
循环,因此我们得到了所有组合,而不是预期的。我们可以遍历行的序列,将其用作索引以提取每一列及其元素paste
。
for(i in seq_len(nrow(df1))){
print(paste("This year is", df1$x[i], df1$y[i], "color", df1$z[i]))
}
#[1] "This year is 5 apple color green"
#[1] "This year is 7 banana color yellow"
#[1] "This year is 13 mango color red"
df1 <- structure(list(x = c(5L, 7L, 13L), y = c("apple", "banana", "mango"
), z = c("green", "yellow", "red")), .Names = c("x", "y", "z"
), class = "data.frame", row.names = c("1", "2", "3"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句