【问题标题】:replace a column of factor data to a column of numeric data.将一列因子数据替换为一列数值数据。
【发布时间】:2025-12-06 23:05:01
【问题描述】:

我有一列因子数据为“001:0 - 3.8979”和“002:3.879-6.528”。在 10000 个观测值中有 61 个。我想用每个范围的平均值替换这些因素,我已经计算并保存在文本文件中作为数值列。因此,“001:0-3.8939”变为 1.9489,依此类推。

如何快速做到这一点?

【问题讨论】:

    标签: r


    【解决方案1】:

    不需要外部文件,就可以了

    ranges <- c("001:0 - 3.8979", "002: 3.879-6.528", "003: 7.528-10.356")
    
    result <- sapply(ranges, function(r){
           # Split by ":" to remove the index, then take the second element
           # and split it by "-".
           values <- strsplit(strsplit(r, ":")[[1]][2], "-")
           # Return the mean (note you need to unlist the result of strsplit)
           mean(as.numeric(unlist(values)))
           })
    

    【讨论】:

    • +1 我在sapply(strsplit(ranges, ":|-"), function(x) mean(as.numeric(x[2:3]))) 的行中考虑得更多。