我必须使用相同长度的矢量[1:216],我想根据一些规则将它们组合成1个矢量。
理由:我从抓取页面获取两个向量以获取描述。现在,描述被放置在一个没有唯一名称的框中,并且在我的所有观察中出现在2个不同的位置(因此也有2个不同的选择器小工具标识符)。我已经抓取了两个位置并从它们创建了2个变量,我现在想要将它们组合成1个向量。
这是向量看的时刻:
vect_1
[1] Description 1
[2] NA
[3] Description 3
vect_2
[1] ""
[2] Description 2
[3] ""
因此,我的代码需要指定,如果NA或""然后从其他向量中观察,否则使用此向量的描述。我怎么能这样做?
我的输出应如下所示:
vect_3
[1] Description 1
[2] Description 2
[3] Description 3
非常感谢提前!
答案 0 :(得分:1)
假设向量长度相等,并且其中一个配对元素将始终为文本字符串而另一个将始终为NA或"",则应执行以下操作。如果情况并非如此,您可能需要稍微更改一下。
vect_1 <- c("Description 1", NA, "Description 3")
vect_2 <- c("", "Description 2", "")
vect_combined <- ifelse(!is.na(vect_1) & vect_1 != "", vect_1, vect_2)
vect_combined # Print
#> [1] "Description 1" "Description 2" "Description 3"
答案 1 :(得分:0)
请通过以下解决方案:
vect_1=c("Description 1",NA,"Description 3")
vect_1
[1] "Description 1" NA "Description 3"
vect_2=c("","Description 2","")
vect_2
[1] "" "Description 2" ""
vect_3=c() # Create an empty vector
for(i in 1:length(vect_1)){
if(is.na(vect_1[i])){ # If value in vect_1 is NA
vect_3=c(vect_3,vect_2[i]) # Look into vect_2
}
else{ # Else
vect_3=c(vect_3,vect_1[i]) # Copy value from vect_1
}
}
vect_3 # Print vect_3
[1] "Description 1" "Description 2" "Description 3"
希望您更容易理解。
答案 2 :(得分:0)
尝试dplyr::coalesce
vec1 <- c("Description 1", NA, "Description 3")
vec2 <- c("", "Description 2", "")
dplyr::coalesce(vec1, vec2)
# [1] "Description 1" "Description 2" "Description 3"
以下内容更安全,因为""
可能被视为有意义的值 - 使用na_if(vec, value)
dplyr::coalesce(na_if(vec1, ""), na_if(vec2, ""))