簡體   English   中英

使用R中帶有兩個變量的apply擴展文本

[英]Extend text using apply with two variables in R

我需要使用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 # result 2塊中那樣,這將是編寫一種以“適當”方式重用每個變量以編寫文本的循環的方式嗎?

這是一個快速的基本r代碼:

 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,";"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM