Reputation: 11499
I have two arrays
chemArr = c("water","oil",...(lots of values omitted)...,"hydrogen")
timeArr = c("0", "8hr", "12hr", "24hr", "36hr", "48hr", "72hr")
and I would like to build a data frame
chem 0 8hr ... 72hr
water f("water", "0") f("water", "8hr") ...
...
where f
is a function I have written. Is there a good way to do this in R?
In my particular case it would be more efficient to make a function taking chem
and returning a column for each time, since each of these share calculations. But since the total time required is small I could do it some other way if it's more convenient.
Upvotes: 1
Views: 1204
Reputation: 11514
To illustrate the solutions discussed in the comments:
one <- letters[1:3]
two <- letters[4:6]
one
[1] "a" "b" "c"
two
[1] "d" "e" "f"
mapply(paste0, one, two)
a b c
"ad" "be" "cf"
mapply(paste0, sort(rep(one, length(two))), two)
a a a b b b c c c
"ad" "ae" "af" "bd" "be" "bf" "cd" "ce" "cf"
mapply(paste0, one, list(two)) # courtesy of @thelatemail
a b c
[1,] "ad" "bd" "cd"
[2,] "ae" "be" "ce"
[3,] "af" "bf" "cf"
outer(one, two, paste0) # courtesy of @akrun
[,1] [,2] [,3]
[1,] "ad" "ae" "af"
[2,] "bd" "be" "bf"
[3,] "cd" "ce" "cf"
Upvotes: 3
Reputation: 263499
I'd suggest using expand.grid
, which creates a "long form" of all 2-way combination, and then use mapply to create the values from the function:
chemArr = c("water","oil","hydrogen")
timeArr = c("0", "8hr", "12hr", "24hr", "36hr", "48hr", "72hr")
mygrid <- expand.grid(chemArr, timeArr)
mygrid <- expand.grid(chems = chemArr, times = timeArr)
str(mygrid)
#'data.frame': 21 obs. of 2 variables:
# $ chems: Factor w/ 3 levels "water","oil",..: 1 2 3 1 2 3 1 2 3 1 ...
# $ times: Factor w/ 7 levels "0","8hr","12hr",..: 1 1 1 2 2 2 3 3 3 4 ...
# - attr(*, "out.attrs")=List of 2
# ..$ dim : Named int 3 7
# .. ..- attr(*, "names")= chr "chems" "times"
# ..$ dimnames:List of 2
# .. ..$ chems: chr "chems=water" "chems=oil" "chems=hydrogen"
# .. ..$ times: chr "times=0" "times=8hr" "times=12hr" "times=24hr" ...
mygrid$f_value <- mapply(f, mygrid$chems, mygrid$times)
Upvotes: 3