2013-10-30 23 views
0

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

如何快速做到这一点?

回答

3

在不需要外部文件,这会做

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))) 
     }) 
+2

+1我对'sapply(strsplit(范围的线条思路更加 “:| - ”),函数(x)的平均(as.numeric(X [2:3])))'。 – A5C1D2H2I1M1N2O1R2T1

相关问题