从一个向量中删除r中另一个向量的所有元素

时间:2016-10-14 06:35:04

标签: r vector

我有2个载体

vec_1
 [1]  2  3  4  5  6  7  8  9 10 11 12 13 14  2  3  4  5  6  7  8  9 10 11 12 13 14  2  3  4  5  6  7  8  9
[35] 10 11 12 13 14  2  3  4  5  6  7  8  9 10 11 12 13 14

vec_2
 [1] 12  3 13  3 14  4 10  8  9  5  7  5 13 11  6 10  8  8 14 12  6 11  8  5  3  6

我想从vec_2删除vec_1的所有元素 当然,函数setdiff并非如此,因为例如vec_2中有两个10s值。我想只删除10个(不是所有4个值的10个)。

编辑:预期产出:

vec_1
[1] 2 2 2 2 3 4 4 4 5 6 7 7 7 9 9 9 10 10 11 11 12 12 13 13 14 14

我怎样才能在r?

中这样做

4 个答案:

答案 0 :(得分:2)

以下是<html> <head> <title>Get images from db</title> </head> <body> <?php $servername = "localhost"; $username = "root"; $password = ""; $db="uni"; $conn = new mysqli( $servername, $username, $password, $db ); if ( $conn->connect_error ) die( "Connection failed: " . $conn->connect_error ); $result = $conn->query( "SELECT * FROM `upload_img`" ); while( $rs = $result->fetch_object() ){ echo " <img src='{$rs->img_path}' /> <br />"; } ?> </body> </html>

的一个想法
union

答案 1 :(得分:2)

当然,不是最好的解决方案,但这是一种方式。

我创建了一个简化的例子。

vec1 <- c(1, 2, 3, 1, 1, 5)
vec2 <- c(1, 3, 5)

#Converting the frequency table to a data frame
x1 <- data.frame(table(vec1))
x2 <- data.frame(table(vec2))

#Assuming your vec1 has all the elements present in vec2
new_df <- merge(x1, x2, by.x = "vec1", by.y = "vec2", all.x = TRUE)
new_df

#  vec1 Freq.x Freq.y
#1    1      3      1
#2    2      1      NA
#3    3      1      1
#4    5      1      1

#Replacing NA's by 0

new_df[is.na(new_df)] <- 0

#Subtracting the frequencies of common elements in two vectors
final <- cbind(new_df[1], new_df[2] - new_df[3])
final

# vec1  Freq.x
#1    1      2
#2    2      1
#3    3      0
#4    5      0

#Recreating a new vector based on the final dataframe

rep(final$vec1, times = final$Freq.x)
# [1] 1 1 2

答案 2 :(得分:1)

您可以使用简单的for循环执行此操作:

for(i in 1:length(vec2)){
    i=which(vec1 %in% vec2[i])[1]
    vec1=vec1[-i]
}

您只需识别第一个位置并从原始矢量中删除。

答案 3 :(得分:0)

你也可以试试这个:

for (el in vec2[vec2 %in% intersect(vec1, vec2)])
  vec1 <- vec1[-which(vec1==el)[1]]
sort(vec1)
 #[1]  2  2  2  2  3  4  4  4  5  6  7  7  7  9  9  9 10 10 11 11 12 12 13 13 14 14
相关问题