如何在R中将循环生成的材料保存到环境中

时间:2016-05-27 20:57:14

标签: r

我在R中编写了一个简单的循环,用恒定的LETTERS生成96孔板的布局。

for (alpha in LETTERS[1:8]){
  print(paste(alpha, 1:12, sep=""))
}

如何修改此项以将生成的板图保存为环境变量,理想情况下是矩阵?我希望它能直接创建环境变量并避免使用save& read.table combo。

3 个答案:

答案 0 :(得分:2)

首先,您可以使用sapply()一行快速轻松地完成此操作。

m1 <- t(sapply(LETTERS[1:8], paste0, 1:12, USE.NAMES = FALSE))

但是你想使用for()循环。因此,您可以先创建一个具有所需尺寸的空字符矩阵,然后在循环中指定行。

m2 <- matrix("", 8, 12)
for(i in 1:8) {
    m2[i, ] <- paste0(LETTERS[i], 1:12)
}

identical(m1, m2)
# [1] TRUE

m1m2是以下矩阵:

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] "A1" "A2" "A3" "A4" "A5" "A6" "A7" "A8" "A9" "A10" "A11" "A12"
[2,] "B1" "B2" "B3" "B4" "B5" "B6" "B7" "B8" "B9" "B10" "B11" "B12"
[3,] "C1" "C2" "C3" "C4" "C5" "C6" "C7" "C8" "C9" "C10" "C11" "C12"
[4,] "D1" "D2" "D3" "D4" "D5" "D6" "D7" "D8" "D9" "D10" "D11" "D12"
[5,] "E1" "E2" "E3" "E4" "E5" "E6" "E7" "E8" "E9" "E10" "E11" "E12"
[6,] "F1" "F2" "F3" "F4" "F5" "F6" "F7" "F8" "F9" "F10" "F11" "F12"
[7,] "G1" "G2" "G3" "G4" "G5" "G6" "G7" "G8" "G9" "G10" "G11" "G12"
[8,] "H1" "H2" "H3" "H4" "H5" "H6" "H7" "H8" "H9" "H10" "H11" "H12"

答案 1 :(得分:1)

使用outer功能:

nameMatrix <- outer(LETTERS[1:8], 1:12, paste, sep = "")
nameMatrix
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] "A1" "A2" "A3" "A4" "A5" "A6" "A7" "A8" "A9" "A10" "A11" "A12"
[2,] "B1" "B2" "B3" "B4" "B5" "B6" "B7" "B8" "B9" "B10" "B11" "B12"
[3,] "C1" "C2" "C3" "C4" "C5" "C6" "C7" "C8" "C9" "C10" "C11" "C12"
[4,] "D1" "D2" "D3" "D4" "D5" "D6" "D7" "D8" "D9" "D10" "D11" "D12"
[5,] "E1" "E2" "E3" "E4" "E5" "E6" "E7" "E8" "E9" "E10" "E11" "E12"
[6,] "F1" "F2" "F3" "F4" "F5" "F6" "F7" "F8" "F9" "F10" "F11" "F12"
[7,] "G1" "G2" "G3" "G4" "G5" "G6" "G7" "G8" "G9" "G10" "G11" "G12"
[8,] "H1" "H2" "H3" "H4" "H5" "H6" "H7" "H8" "H9" "H10" "H11" "H12"

如果您想进一步将它们指定为变量名称,可以创建一个列表:

li <- setNames(vector("list", 96), nameMatrix)
head(li)
$A1
NULL

$B1
NULL

$C1
NULL

$D1
NULL

$E1
NULL

$F1
NULL

例如,您可以将这些变量作为li$A1来访问。

答案 2 :(得分:0)

这样的东西?

df <- expand.grid(LETTERS[1:8], 1:12)
v <- paste0(df[[1]], df[[2]])
m <- matrix(v, 8, 12)

> m
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] "A1" "A2" "A3" "A4" "A5" "A6" "A7" "A8" "A9" "A10" "A11" "A12"
[2,] "B1" "B2" "B3" "B4" "B5" "B6" "B7" "B8" "B9" "B10" "B11" "B12"
[3,] "C1" "C2" "C3" "C4" "C5" "C6" "C7" "C8" "C9" "C10" "C11" "C12"
[4,] "D1" "D2" "D3" "D4" "D5" "D6" "D7" "D8" "D9" "D10" "D11" "D12"
[5,] "E1" "E2" "E3" "E4" "E5" "E6" "E7" "E8" "E9" "E10" "E11" "E12"
[6,] "F1" "F2" "F3" "F4" "F5" "F6" "F7" "F8" "F9" "F10" "F11" "F12"
[7,] "G1" "G2" "G3" "G4" "G5" "G6" "G7" "G8" "G9" "G10" "G11" "G12"
[8,] "H1" "H2" "H3" "H4" "H5" "H6" "H7" "H8" "H9" "H10" "H11" "H12"