*适用于两个向量的组合

时间:2013-04-10 04:41:35

标签: r

问题

我可以使用哪种应用函数从数据转到结果?

数据

start      <- "My name is"
name.first <- c("John","Jane")
name.last  <- c("Doe","Smith")
end        <- "and I am a person."

期望结果

result.1 <- c("My name is John Doe and I am a person",
              "My name is Jane Doe and I am a person",
              "My name is John Smith and I am a person",
              "My name is Jane Smith and I am a person")

result.2 <- as.list(desired.1)

我虚弱的尝试......

我认为mapply会在这里做到这一点,但它只产生两个输出,而不是我想要的四个输出。

> mapply(function(x,y, start, end) paste(start, x, y, end, sep = " "),
+        name.first, 
+        name.last, 
+        MoreArgs = list(start, end),
+        USE.NAMES = FALSE)
[1] "My name is John Doe and I am a person."  
[2] "My name is Jane Smith and I am a person."

2 个答案:

答案 0 :(得分:2)

您只需要outerpaste

start <- "My name is"
name.first <- c("John", "Jane")
name.last <- c("Doe", "Smith")
end <- "and I am a person."

as.vector(outer(name.first, name.last, paste))
## [1] "John Doe"   "Jane Doe"   "John Smith" "Jane Smith"

paste("My name is ", as.vector(outer(name.first, name.last, paste)))
## [1] "My name is  John Doe"   "My name is  Jane Doe"   "My name is  John Smith" "My name is  Jane Smith"

paste("My name is ", as.vector(outer(name.first, name.last, paste)), " and I am a person")
## [1] "My name is  John Doe  and I am a person"   "My name is  Jane Doe  and I am a person"  
## [3] "My name is  John Smith  and I am a person" "My name is  Jane Smith  and I am a person"

as.list(paste("My name is ", as.vector(outer(name.first, name.last, paste)), " and I am a person"))
## [[1]]
## [1] "My name is  John Doe  and I am a person"
## 
## [[2]]
## [1] "My name is  Jane Doe  and I am a person"
## 
## [[3]]
## [1] "My name is  John Smith  and I am a person"
## 
## [[4]]
## [1] "My name is  Jane Smith  and I am a person"
## 

正如您在尝试中看到的那样,mapply将仅匹配其输入向量的相应元素,即对于第一个iteration,它将使用所有输入向量的第一个元素,对于第二个iteration它将使用所有输入向量的第二个元素,依此类推。

答案 1 :(得分:2)

paste( start = "My name is",
        apply( expand.grid(name.first = c("John","Jane"),
                           name.last  = c("Doe","Smith"), 
                           stringsAsFactors=FALSE),
               1, paste, collapse=" "),
        end  = "and I am a person.")

[1] "My name is John Doe and I am a person."   "My name is Jane Doe and I am a person."  
[3] "My name is John Smith and I am a person." "My name is Jane Smith and I am a person."