R表示循环通过向量,如果下标超出界限变为某个值



我有一个向量列表,其中的值有时在1到7之间,有时在1和5之间。我想循环使用它们,并使用函数table获得频率计数,然后将这些值放入数据帧中,但我收到了subscript out of bounds错误。它这样做是因为它需要一个integer值。当这种情况发生时,我希望将整数值设置为0。

有没有一个简单的函数可以封装在integer值周围,例如返回0somefunction(t[[6]])

#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

我们可以在设置list的名称后,将list转换为具有stack的两列data.frame,然后应用table

table(stack(setNames(vectors, seq_along(vectors)))[2:1])
#  values
#ind  1  2  3  4  5  6  7
#  1  2  2  3  2  3  4  5
#  2  2  2  3  2 12  0  0
#  3  2  2  3  2  3  4  5

以上将是一个table对象。如果我们需要转换为data.frame(不需要重新整形为"长"格式(

as.data.frame.matrix(table(stack(setNames(vectors, seq_along(vectors)))[2:1]))

在这里,我们只应用table一次,它会更高效,也不那么复杂,因为它会自动找到唯一的值。如果我们是循环的,那么我们必须事先找到唯一的值,以添加要算作0 的缺失级别


通过循环,我们可以将单个list元素转换为factor,其中levels指定为所有元素的unique

un1 <- sort(unique(unlist(vectors)))
t(sapply(vectors, function(x) table(factor(x, levels = un1))))

for循环中,我们可以使用rbind,但对于rbind,我们希望列名相同或长度相同。因此,一个选项是dplyr中的bind_rows,而不是rbind

library(dplyr)
df <- data.frame()
for(i in seq_along(vectors)) {
tbl1 <- table(vectors[[i]])
df <- bind_rows(df, tbl1)
}

默认情况下,对于找不到的列,bind_rows将使用NA填充。然后我们将NA替换为0

df[is.na(df)] <- 0

但是,这并不是一个有效的选择,正如调用table一次所显示的那样

相关内容

最新更新