R:将数组中的字符串转换为整数

时间:2018-08-01 13:32:05

标签: arrays r

我已经使用split然后使用do.call(abind, list(myMat, along = 3)将矩阵转换为数组。在下面的示例中,如何仅将“ lat”和“ long”列转换为整数?

来自...

> myArray [1:5, , "sp1"]            
          sp      long         lat        
    3100 "sp1" "-60,683889" "2,839167" 
    3101 "sp1" "-60,6733"   "2,81972"  
    3102 "sp1" "-60,997222" "1,402222" 
    3103 "sp1" "-51,45"     "0,70"     
    3104 "sp1" "-48,5233"   "-0,716667"
    > 

到...

> myArray [1:5, , "sp1"]   
      sp      long         lat        
3100 "sp1" -60,683889 2,839167 
3101 "sp1" -60,6733   2,81972  
3102 "sp1" -60,997222 1,402222 
3103 "sp1" -51,45     0,70    
3104 "sp1" -48,5233   -0,716667
> 

1 个答案:

答案 0 :(得分:1)

数组不能包含字符和数字元素。您可以改为删除sp列,因为它已经在名称中了。

a <- myArray[, -1, ]
array(as.numeric(sub(",", ".", a)), dim(a), dimnames(a))

给予:

, , sp1

          long       lat
3100 -60.68389  2.839167
3101 -60.67330  2.819720
3102 -60.99722  1.402222
3103 -51.45000  0.700000
3104 -48.52330 -0.716667

, , sp2

          long       lat
3100 -60.68389  2.839167
3101 -60.67330  2.819720
3102 -60.99722  1.402222
3103 -51.45000  0.700000
3104 -48.52330 -0.716667

注意

myArray <- 
structure(c("sp1", "sp1", "sp1", "sp1", "sp1", "-60,683889", 
"-60,6733", "-60,997222", "-51,45", "-48,5233", "2,839167", "2,81972", 
"1,402222", "0,70", "-0,716667", "sp2", "sp2", "sp2", "sp2", 
"sp1", "-60,683889", "-60,6733", "-60,997222", "-51,45", "-48,5233", 
"2,839167", "2,81972", "1,402222", "0,70", "-0,716667"), .Dim = c(5L, 
3L, 2L), .Dimnames = list(c("3100", "3101", "3102", "3103", "3104"
), c("sp", "long", "lat"), c("sp1", "sp2")))