我试着写skript。我有ip地址和时间。从ip地址我想创建3个数字,从时间上我想要几小时和几分钟。例如:158.188.10.251和结果:158,158188,15818810。我有这段代码:
data = matrix(
c("158.188.10.251","15/Oct/2017:14:06:29 +0200",
"207.46.13.6","15/Oct/2017:14:35:55 +0200",
"157.55.39.32","15/Oct/2017:23:43:49 +0200"
),
nrow=3,
ncol=2,
byrow = TRUE)
newdata <- matrix(, nrow = 3, ncol = 5)
for (i in 1:3){
#split first item to colums
a <- strsplit(data[i,1], ".", fixed = TRUE)
#create
a2 <- paste(a[1],a[2],sep="")
a3 <- paste(a2,a[3],sep="")
#from string to int
newdata[i, 1]<-strtoi(a[1], base = 0L)
newdata[i, 2]<-strtoi(a2, base = 0L)
newdata[i, 3]<-strtoi(a3, base = 0L)
#choose hourse and minute from time
c <- substr(data[i,2], 13, 14)
newdata[i, 4]<- strtoi(c, base = 0L)
d <- substr(data[i,2], 16, 17)
newdata[i, 5]<- strtoi(d, base = 0L)
}
问题是newdata看起来像:
> print (newdata)
[,1] [,2] [,3] [,4] [,5]
[1,] NA NA NA 14 6
[2,] NA NA NA 14 35
[3,] NA NA NA 23 43
值a是一个包含4个字符的列表
[[1]]
[1] "157" "55" "39" "32"
但是当我尝试打印一个这样的字符时:
> print (a[1,1])
Error in a[1, 1] : incorrect number of dimensions
> print (a[1,])
Error in a[1, ] : incorrect number of dimensions
> print (a[,1])
Error in a[, 1] : incorrect number of dimensions
如何解决这个问题?
答案 0 :(得分:1)
这个怎么样?
data = matrix(
c("158.188.10.251","15/Oct/2017:14:06:29 +0200",
"207.46.13.6","15/Oct/2017:14:35:55 +0200",
"157.55.39.32","15/Oct/2017:23:43:49 +0200"
),
nrow=3,
ncol=2,
byrow = TRUE)
ips <- matrix("",ncol=3,nrow=nrow(data))
times <- matrix("",ncol=2,nrow=nrow(data))
for(i in 1:nrow(data)){
tip <- unlist(strsplit(data[i,1],"\\."))
ttime <- unlist(strsplit(data[i,2],":"))
ips[i,1] <- tip[1]
ips[i,2] <- paste0(tip[1:2],collapse="")
ips[i,3] <- paste0(tip[1:3],collapse="")
times[i,1] <- ttime[2]
times[i,2] <- ttime[3]
}
ips
times