我有两个数组
chemArr = c("water","oil",...(lots of values omitted)...,"hydrogen")
timeArr = c("0", "8hr", "12hr", "24hr", "36hr", "48hr", "72hr")
我想构建一个数据框
chem 0 8hr ... 72hr
water f("water", "0") f("water", "8hr") ...
...
其中f
是我写的函数。有没有一种很好的方法在R中做到这一点?
在我的特定情况下,使用chem
函数并每次返回一列更有效,因为每个函数共享计算。但由于所需的总时间很短,如果它更方便的话,我可以用其他方式做。
答案 0 :(得分:3)
说明评论中讨论的解决方案:
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"
答案 1 :(得分:3)
我建议使用expand.grid
,这会创建一个&#34;长形式&#34;所有双向组合,然后使用mapply从函数创建值:
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)