(我知道循环不是R中的首选,但这是我能想到的最好的选择)
我正在尝试遍历向量并在满足条件时返回向量值。
一旦满足下一个条件,我想放弃变量。
到目前为止,我已经达到了以下目标:
df = c(1:10)
sig = function (df) {
pos = integer(10)
for (i in 1:10) {
if (df[i] > 3 ) { # Once df[i] is bigger than 3 store the value of df[i]
pos[i] = df[i]
}
else if(df[i] < 7 ){ # Keep value of df[i] until next condition is met
pos[i] = pos[i - 1]
}
else{pos[i] = 0} # set the value back to 0
}
reclass(pos,df)
}
sig(df)
我收到以下错误Error in pos[i] <- pos[i - 1] : replacement has length zero
答案应如下所示:
df sig
1 0
2 0
3 0
4 4
5 4
6 4
7 0
8 0
9 0
10 0
有什么想法吗?
答案 0 :(得分:1)
实现输出的另一种方式:
import cv2
import numpy as np
img1 = cv2.resize(cv2.imread("./spot/image1.jpg"), (224, 224)).astype(np.float32)
img2 = cv2.resize(cv2.imread("./spot/image2.jpg"), (224, 224)).astype(np.float32)
diff = cv2.subtract(img1, img2)
result = not np.any(diff)
if result is True:
print "The images are the same"
else:
cv2.imwrite("result.jpg", diff)
print "the images are different"
关于您的问题
pos = integer(10)
pos[df>3 & df<7]<-df[which.max(df>3 & df<7)]
cbind(df,pos)
df pos
[1,] 1 0
[2,] 2 0
[3,] 3 0
[4,] 4 4
[5,] 5 4
[6,] 6 4
[7,] 7 0
[8,] 8 0
[9,] 9 0
[10,] 10 0
从1开始,在for循环中你有i
,所以pos[i-1]
但是列表从1开始。
试试这个:
pos[0]
sig = function (df) {
pos = integer(10)
for (i in 1:10) {
if (df[i] > 3 ) { # Once df[i] is bigger than 3 store the value of df[i]
pos[i] = df[i]
}
else if(df[i] < 7 ){ # Keep value of df[i] until next condition is met
if(i>1) {
pos[i] = pos[i - 1]
} else
{
pos[i]=0
}
}
else{pos[i] = 0} # set the value back to 0
}
return(cbind(df,pos))
}
指示已添加
你的输出:
return
输出与预期的输出不同,因此您必须在for循环内的逻辑中找到其他错误。
答案 1 :(得分:1)
你可以用data.table来做,这是方法
Display()
这是输出
DisplayText()
答案 2 :(得分:1)
这是一种不使用for
循环的可能解决方案。相反,您可以使用rle
:
a <- c(1:10)
r <- rle(a > 3 & a < 7)
r$values <- ifelse(r$values, a[head(cumsum(c(1, r$lengths)), -1)], 0)
inverse.rle(r)
[1] 0 0 0 4 4 4 0 0 0 0
请注意,这仅在向量排序时才有效。
另一个例子:
> a <- c(4, 7, 9, 6, 5, 8, 10, 2, 3, 1)
> r <- rle(a %% 2 == 0)
> r$values <- ifelse(r$values, a[head(cumsum(c(1, r$lengths)), -1)], 0)
> inverse.rle(r)
[1] 4 0 0 6 0 8 8 8 0 0
答案 3 :(得分:1)
您也可以使用ifelse
df <- c(1:10)
ifelse(df > 3 & df < 7, df[which(df > 3)][1], 0)
# [1] 0 0 0 4 4 4 0 0 0 0