在R中使用paste合并列后将列类型转换为整数的方法
解决方案:保留数值类型的行合并方法
你当前用paste()会把数值拼接成字符串,导致类型转为character。要保留原始数值类型,应该把每个分组下的数值存储为列表列(每个单元格是一个数值向量),而非字符串。
代码实现
library(dplyr) # 构建示例数据框(模拟你的原始数据) result_3p <- tibble( `3_utr_start` = c(299336, 299339), `3_utr_end` = c(303353, 303360), count = c(1268, 1280), freq = c(13.66, 14.25), entrezgene_id = c(55344, 55346) ) # 按entrezgene_id分组,将各列转为列表列保留数值类型 result_final <- result_3p %>% group_by(entrezgene_id) %>% summarize( `3_utr_start` = list(`3_utr_start`), `3_utr_end` = list(`3_utr_end`), count = list(count), freq = list(freq) ) %>% relocate(entrezgene_id, .before = everything()) # 调整列顺序匹配目标格式
验证类型
查看结果的列类型,确认数值类型未丢失:
str(result_final)
输出示例:
tibble [2 × 5] (S3: tbl_df/tbl/data.frame) $ entrezgene_id: num [1:2] 55344 55346 $ 3_utr_start :List of 2 ..$ : int 299336 ..$ : int 299339 $ 3_utr_end :List of 2 ..$ : int 303353 ..$ : int 303360 $ count :List of 2 ..$ : int 1268 ..$ : int 1280 $ freq :List of 2 ..$ : num 13.66 ..$ : num 14.25
按需转换为展示用字符串
如果只是需要在输出/展示时呈现为空格分隔的格式,但后续还要做数值运算,可以临时转换:
# 生成用于展示的字符型版本 result_display <- result_final %>% mutate(across(-entrezgene_id, ~sapply(., paste, collapse = " ")))
此时result_display是用于查看的字符格式,而result_final保留了原始数值类型,支持后续的数值分析操作。
列表列的数值运算示例
列表列可以直接进行数值操作,比如提取元素、计算统计值:
# 提取第一个基因的3_utr_start第一个数值 result_final$`3_utr_start`[[1]][1] # 计算每个基因的count均值 result_final %>% mutate(mean_count = sapply(count, mean))
内容的提问来源于stack exchange,提问作者Saabu
相关产品推荐
相关产品推荐

