[英]how to read letters as numbers in R
我有一些數據在戰艦游戲的代碼中,例如: A0,A1,B0,B4,K12
,我想將它們轉換為坐標點。 字母應為x坐標,數字應為y坐標。 除此之外,我應該將字母轉換為數字以使其相乘。 像那樣:
A0 = 0 , 0;
A1 = 0 , 15;
A2 = 0 , 30;
B3 = 15 , 45
干得好:
BattleshipConversion <- function(mystring)
{
return(c(which(LETTERS==substr(mystring,1,1))-1,as.integer(substr(mystring,2,3)))*15)
}
結果:
>BattleshipConversion("B1")
15 15
>BattleshipConversion("A10")
0 150
那么上面發生了什么?
LETTERS
是大寫字母R的預生成向量。 which
采用字母在該向量中的索引位置,因此which(LETTERS=='A')
將得出1。我們從中減去1。 substr
是一個從字符串中提取子字符串的函數,以string
, start
和stop
作為參數。 計數從第一個元素開始,在R中為substring(mystring,1,1)
接受substring(mystring,1,1)
的第一個字符元素,然后在此停止。 as.integer
只是將存儲為字符的1-2位整數轉換為正確的整數格式。 c()
將所有內容保存在組合向量中,根據OP的規范,所有內容都乘以15 請注意,這假設您的輸入字符串格式正確。 它只能工作到Z
和99
,即在AA14
或B101
上將失敗。 您可能需要添加一些保護措施。
假設您有以下職位:
pos<-c("A0","A1","A2","B3","K12")
您可以:
require(data.table) #just to use tstrsplit
res<-setNames(as.data.frame(tstrsplit(pos,"(?<=[A-Z])",perl=TRUE),stringsAsFactors=FALSE),c("x","y"))
res[[1]]<-(match(res[[1]],LETTERS)-1)*15
res[[2]]<-as.numeric(res[[2]])*15
cbind(pos,res)
# pos x y
#1 A0 0 0
#2 A1 0 15
#3 A2 0 30
#4 B3 15 45
#5 K12 150 180
這是矢量化的,可以輕松擴展為雙字母:
fun <- function(s) {
x <- gsub("[[:digit:]]", "", s) #remove numbers
y <- gsub("[[:alpha:]]", "", s) #remove letters
x <- match(x, LETTERS) - 1 #match against letters
y <- as.integer(y)
cbind(x = x * 15, y = y * 15)
}
fun(c("A0", "A1", "A2", "B3"))
# x y
#[1,] 0 0
#[2,] 0 15
#[3,] 0 30
#[4,] 15 45
這是一個dplyr的答案
library(dplyr)
library(tidyr)
library(rex)
template = rex(capture(letters),
capture(numbers) )
coordinates = c("A0","A1","B0","B4","K12")
letter_frame =
data_frame(LETTERS,
x_small = 1:26)
result =
data_frame(coordinate = coordinates) %>%
extract(coordinate, c("letter", "y_small"), template, convert = TRUE) %>%
left_join(letter_frame) %>%
mutate(x = x_small*15,
y = y_small*15)
BSconverter <- function(str){
let <- substr(str,1,1)
num <- as.integer(substr(str,2,nchar(str))) * 15
letnum <- (which(LETTERS==let)-1) * 15
c(letnum, num)
}
> BSconverter("K12")
[1] 150 180
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.