2013-10-30 22 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

相關問題