R语言:如何将数据框author列的list长度转为数值型authorcount列?
解决R中list转整数列的问题
针对你遇到的Map()返回list类型列的问题,有几种简便的解决方式,可直接得到整数型的authorcount列:
方法1:基础R的
unlist()转换
先通过Map()获取每个子数据框的行数,再用unlist()把list转成向量,最后显式转为整数类型:papers$authorcount <- as.integer(unlist(Map(nrow, papers$author)))方法2:用
purrr包的map_int()(推荐)
如果你习惯使用tidyverse工具链,purrr::map_int()会直接返回整数向量,无需额外转换:library(purrr) papers$authorcount <- map_int(papers$author, nrow)方法3:基础R的
sapply()sapply()默认会将结果简化为向量,后续转成整数即可:papers$authorcount <- as.integer(sapply(papers$author, nrow))
以上三种方法都能帮你得到整数型的authorcount列,替代原来的list类型。
内容的提问来源于stack exchange,提问作者Nicholas Marshall
相关产品推荐
相关产品推荐

