【问题标题】:Extend text using apply with two variables in R在 R 中使用带有两个变量的 apply 扩展文本
【发布时间】: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 &lt;- "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 块中的文本?

【问题讨论】:

    标签: r dplyr apply sapply


    【解决方案1】:

    这是一个快速的基本 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,";"))
    

    【讨论】:

    • 谢谢!完美运行!我还添加了collapse = "\n" 以将它们打印在不同的行中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多