【发布时间】:2020-07-12 19:39:20
【问题描述】:
我有一个向量列表,有时值的范围是 1 到 7,有时是 1 到 5。我想遍历它们并使用函数 table 获取频率计数,然后将这些值放入数据框中,但我收到subscript out of bounds 错误。它这样做是因为它需要一个integer 值。发生这种情况时,我想将整数值设置为 0。
是否有一个简单的函数可以环绕integervalue,例如somefunction(t[[6]]) 返回 0?
#list of vectors, the first has values 1 to 7, the second has 1 to 5,
#the third is 1 to 7 again and is only included to show that my real problem has many
# more vectors to evaluate
vectors<-list(c(1,1,2,2,3,3,3,4,4,5,5,5,6,6,6,6,7,7,7,7,7),
c(1,1,2,2,3,3,3,4,4,5,5,5,5,5,5,5,5,5,5,5,5),
c(1,1,2,2,3,3,3,4,4,5,5,5,6,6,6,6,7,7,7,7,7))
#empty data frame
df<-data.frame()
#loop through list of vectors and get frequncy count per list
for (i in 1:length(vectors)) {
#count frquency of each value as variable t
t<-table(vectors[[i]])
#put frequency count of each value in the data frame - the problem is
#that in the second vector, there are only values of 1 to 5, so t[[6]]
#reports "subscript out of bounds". I want to change this to a value of 0
df<-rbind(df,cbind(t[[1]],t[[2]],t[[3]],t[[4]],t[[5]],t[[6]],t[[7]]))
}
df
【问题讨论】: