【发布时间】:2017-12-24 18:02:14
【问题描述】:
我需要在 R 中使用两个变量制作一小段文本。我有以下数据:
library(dplyr)
VAR <- c("Age", "Condition", "Condition2")
FIELDS <- c("", "Option1;Option2", "Set1;Set2")
df <- cbind(VAR, FIELDS) %>%
as_data_frame()
还有一个循环写入文本的函数:
extending <- function(x, VAR){
VARZ <- VAR[!is.na(x)]
sapply(x, function(x){
if(!is.na(x)){
VARZ <- "XXXXX"
opciones <- strsplit(x, ";")
opciones <- opciones[[1]]
opciones2 <- paste(
"From ", VARZ, " here's ", opciones,
sep=""
)
} else {
opciones2 <- ""
}
opciones2
})
}
当我使用带有两个变量的函数时:
extending(df$FIELDS, df$VAR)
结果是这样的:
# result 1
[[1]]
[1] "From XXXXX here's "
$`Option1;Option2`
[1] "From XXXXX here's Option1" "From XXXXX here's Option2"
$`Set1;Set2`
[1] "From XXXXX here's Set1" "From XXXXX here's Set2"
我想要得到的是以下内容:
# result 2
[[1]]
[1] "From Age here's "
$`Option1;Option2`
[1] "From Condition here's Option1" "From Condition here's Option2"
$`Set1;Set2`
[1] "From Condition2 here's Set1" "From Condition2 here's Set2"
但如果我禁用VARZ <- "XXXXX" 行,我会得到完全不同的东西:
# result 3
Option1;Option2 Set1;Set2
[1,] "From Age here's " "From Age here's Option1" "From Age here's Set1"
[2,] "From Condition here's " "From Condition here's Option2" "From Condition here's Set2"
[3,] "From Condition2 here's " "From Condition2 here's Option1" "From Condition2 here's Set1"
我尝试了一些变化,但以更奇怪的结果结束,并且不太了解我在做什么。
这是否是一种编写循环的方法,该循环以“正确”的方式重用每个变量来编写 # result 2 块中的文本?
【问题讨论】: