我需要在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
块中的文本吗?
这是一个快速的基础代码:
VAR <- c("Age", "Condition", "Condition2")
FIELDS=c(" ", "Option1;Option2", "Set1;Set2")
Map(function(x,y)paste("from",x,"here's",y),VAR,strsplit(FIELDS,";"))
$Age
[1] "from Age here's "
$Condition
[1] "from Condition here's Option1" "from Condition here's Option2"
$Condition2
[1] "from Condition2 here's Set1" "from Condition2 here's Set2"
当然,只有当您对名称不感兴趣时,您才能缩短代码:您可以在以后设置
Map(paste,"from",VAR,"here's",strsplit(FIELDS,";"))