将矢量或字符串插入单个矩阵单元格中

时间:2014-05-20 01:57:53

标签: r

我想制作一个矩阵/数组,其中一个单元格包含4个数字,这样如果我在给定单元格上使用length()函数,它将返回观察数量= 4.

感谢任何帮助..

battery <- read.table ( text = "
1 15 130 155 74 180
1 70 34 40 80 75
1 125 20 70 82 58
2 15 150 188 159 126
2 70 126 122 106 115
2 125 25 70 58 45
3 15 138 110 168 160
3 70 174 120 150 139
3 125 96 104 82 60      
")

colnames(battery) <-c("Material","Temperature","First Observation","Second Observation","Third Observation","Fourth Observation")
as.matrix(battery)

life.obs <- array(NA,c(3,3))
as.data.frame(life.obs)

count=0

for (i in 1:nrow(life.obs)) 
{
  life15 <- c(battery[i,3],battery[i,4],battery[i,5],battery[i,6])
  life70 <- c(battery[i+3,3],battery[i+3,4],battery[i+3,5],battery[i+3,6])
  life125 <- c(battery[i+6,3],battery[i+6,4],battery[i+6,5],battery[i+6,6])

  life.obs[i,count+1] <- as.vector(life15) #this is where I am stuck
  life.obs[i,count+2] <- as.vector(life70) 
  life.obs[i,count+3] <- as.vector(life125)

  count=0
}

2 个答案:

答案 0 :(得分:1)

您可以通过添加列表作为列来实现data.frame。

x <- matrix(runif(16,1,100),ncol=4)
xdf <- data.frame(x)
MyList <- list("a"=c(1,4),"b"=c(3,6),"c"=c(4,8,2),"d"=c(7,4))
xdf$MyList <- MyList 
xdf
        X1        X2       X3       X4  MyList
1 39.73090  3.045103 61.45340 86.77167    1, 4
2 90.06798 38.227905 46.19948 70.15402    3, 6
3 90.54852 42.799657 77.85409 89.66850 4, 8, 2
4 65.97255 41.813881 81.49168 51.22093    7, 4

str(xdf[1,5])
List of 1
 $ a: num [1:2] 1 4
# but each cell is a list so to get the length you need
length(xdf[1,5][[1]])
[1] 2

答案 1 :(得分:0)

嗯,数组中的所有项都需要是相同的类型。如果您愿意,可以制作矩阵/列表数组

life.obs<-array(list(), dim=c(3,3))

然后在放置/检索值时要做的重要事情是使用双括号来实际访问元素。例如

life.obs[[i,count+1]] <- life15

所以这也应该是真的

length(life.obs[[1,1]]) == 4
# [1] TRUE