结果的行数不是 R 中向量长度 (arg 2) 的倍数

San*_*n.O 5 r mean outliers dataframe dplyr

我有与此相关的新问题,我的主题 删除 r 中的异常值并考虑名义 var。在新情况下,变量 x 和 x1 具有不同的长度

x <- c(-10, 1:6, 50)
x1<- c(-20, 1:5, 60)
z<- c(1,2,3,4,5,6,7,8)

bx <- boxplot(x)
bx$out

bx1 <- boxplot(x1)
bx1$out


x<- x[!(x %in% bx$out)]
x1 <- x1[!(x1 %in% bx1$out)]


x_to_remove<-which(x %in% bx$out)
x <- x[!(x %in% bx$out)]

x1_to_remove<-which(x1 %in% bx1$out)
x1 <- x1[!(x1 %in% bx1$out)]

z<-z[-unique(c(x_to_remove,x1_to_remove))]
z  

data.frame(cbind(x,x1,z))
Run Code Online (Sandbox Code Playgroud)

然后我收到警告

Warning message:
In cbind(x, x1, z) :
  number of rows of result is not a multiple of vector length (arg 2)
Run Code Online (Sandbox Code Playgroud)

所以在新的数据框中 obs. Z 的值不对应于 x 和 x1。我该如何决定这个问题?这个解决方案对我没有帮助 Rsolnp:在 cbind(temp, funv) 中:结果的行数不是向量长度(arg 1)的倍数 ,或者我只是做错了什么。

编辑

x_to_remove<-which(x %in% bx$out)
x <- x[!(x %in% bx$out)]

x1_to_remove<-which(x1 %in% bx1$out)
x1 <- x1[!(x1 %in% bx1$out)]

z<-z[-unique(c(x_to_remove,x1_to_remove))]
z  

d=data.frame(cbind(x,x1,z))
d
Run Code Online (Sandbox Code Playgroud)

这是错误的警告消息:

In cbind(x, x1, z) :
  number of rows of result is not a multiple of vector length (arg 2)
Run Code Online (Sandbox Code Playgroud)

d

  x x1 z
1 1  1 2
2 2  2 3
3 3  3 4
4 4  4 5
5 5  5 6
6 6  1 2
Run Code Online (Sandbox Code Playgroud)

如何在这 3 列上获得此输出

Na  Na  Na
1   1   2
2   2   3
3   3   4
4   4   5
5   5   6
Na  Na  Na
Na  Na  Na
Run Code Online (Sandbox Code Playgroud)

六行 (d) 是多余的

Ter*_*ror 1

原始 x、x1 和 z 列表中的长度不同是第一个问题,如何说出哪些 z 值与每个 x 和 x1 值相关?

x <- c(-10, 1:6, 50)
x1<- c(-20, 1:5, 60)
z<- c(1,2,3,4,5,6,7,8)
length(x)
[1] 8
length(x1)
[1] 7
length(z)
[1] 8
Run Code Online (Sandbox Code Playgroud)

另一个问题在这里:

x<- x[!(x %in% bx$out)] #remove this
x1 <- x1[!(x1 %in% bx1$out)] #remove this


x_to_remove<-which(x %in% bx$out)
x <- x[!(x %in% bx$out)]

x1_to_remove<-which(x1 %in% bx1$out)
x1 <- x1[!(x1 %in% bx1$out)]
Run Code Online (Sandbox Code Playgroud)

在计算之前先清理xx1x_to_removex1_to_remove

编辑:要实现您想要的输出,请尝试以下代码(/ode 行添加签名注释):

x <- c(-10, 1:6, 50)
x1<- c(-20, 1:5, 60)
z<- c(1,2,3,4,5,6,7,8)

length_max<-min(length(x),length(x1),length(z)) #Added: identify max length before outlier detection

bx <- boxplot(x)
bx1 <- boxplot(x1)

x_to_remove<-which(x %in% bx$out)
x <- x[!(x %in% bx$out)]

x1_to_remove<-which(x1 %in% bx1$out)
x1 <- x1[!(x1 %in% bx1$out)]

z<-z[-unique(c(x_to_remove,x1_to_remove))]

length_min<-min(length(x),length(x1),length(z)) #Minimum length after outlier remove

d=data.frame(cbind(x[1:length_min],x1[1:length_min],z[1:length_min])) #Bind columns
colnames(d)<-c("x","x1","z")

d_NA<-as.data.frame(matrix(rep(NA,(length_max-length_min)*3),nrow=(length_max-length_min))) #Create NA rows
 colnames(d_NA)<-c("x","x1","z")

d<-rbind(d,d_NA) #Your desired output
d
   x x1  z
1  1  1  2
2  2  2  3
3  3  3  4
4  4  4  5
5  5  5  6
6 NA NA NA
7 NA NA NA
Run Code Online (Sandbox Code Playgroud)