给定一个具有n
长度的数据框,我运行了一个apply函数并将结果分配给该数据框上的新列:
my_df$index <- sapply(my_df$local_db_uuid,function(x) which(my_df$remote_db_uuid== x))
但是,我注意到以下几点:
join_ref_id_complete$index %>% length()
# returns length of dataframe rows
与:
join_ref_id_complete$index %>% unlist() %>% length()
# returns less than length of dataframe rows
长度是怎么回事?这些缺失的值吗?
某些list
元素可能没有匹配项并返回integer(0)
,而这些元素在unlist
ing时会被丢弃。用一个简单的例子
lst1 <- list(c(5, 0), c(3, 2, 4), 5)
sapply(lst1, function(x) which(x == 5))
#[[1]]
#[1] 1
#[[2]]
#integer(0)
#[[3]]
#[1] 1
当我们unlist
,第二个元素被删除
unlist(sapply(lst1, function(x) which(x == 5)))
#[1] 1 1
返回length
2而不是3
但是,长度变短只是一个巧合。它可以做得更好
lst1 <- list(c(5, 0, 5, 5), c(3, 2, 4), c(5, 3, 5))
unlist(sapply(lst1, function(x) which(x == 5)))
#[1] 1 3 4 1 3
在这里,length
是5比即越length
的list
。也可能只是巧合而相等
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句