首页 > 解决方案 > R:将数组中的字符串转换为整数

问题描述

split我已经使用then将矩阵转换为数组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
> 

标签: arraysr

解决方案


数组不能包含字符和数字元素的混合。您可以改为删除该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")))

推荐阅读