2

问题

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

数据

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."
4

2 回答 2

2

You just need outer and paste

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"
## 

As you saw in your attempt, mapply will match only corresponding elements of it's input vector i.e. for first iteration it will use first elements of all input vectors, for second iteration it will use second elements of all input vectors and so on.

于 2013-04-10T04:46:54.847 回答
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."
于 2013-04-10T04:59:06.770 回答