R将NA值转换为字符以进行字符串比较
我有一个数据框,它包含两列字符串。目标是查看其中有多少相同,包括R将NA值转换为字符以进行字符串比较,r,string,na,R,String,Na,我有一个数据框,它包含两列字符串。目标是查看其中有多少相同,包括NA值。如果两列都给出了NA,则应将其视为相同 class(df$column_1) # it shows characters length(which(df$column_1 == df$column_2)) # the result exclude the NA rows 试着在is.na之外提问: length(which(x$a == x$b | (is.na(x$a) & is.na(x$b)))) #[1]
NA
值。如果两列都给出了NA,则应将其视为相同
class(df$column_1) # it shows characters
length(which(df$column_1 == df$column_2)) # the result exclude the NA rows
试着在
is.na之外提问:
length(which(x$a == x$b | (is.na(x$a) & is.na(x$b))))
#[1] 2
数据:
x另一种方法是使用idential()
(它有一个很好的属性,idential(NA,NA)=TRUE
)逐项循环:
虚拟数据:
a=c("a",NA,"b")
b=c(NA,NA,"d")
df = data.frame(a, b, stringsAsFactors=FALSE)
代码:
输出:
>count
>1
长度(其中(df$column\u 1==df$column\u 2,x=T))
?太棒了!谢谢它起作用了。这“which(is.na(i)| i)”到底是什么意思?如果两个部分同时na
,那么s.na(x$a)和is.na(x$b)部分将进行测试。或者:使用(df,sum(mappy(idential,a,b))
count = 0
for(i in 1:nrow(df)){
count = count + identical(df[i,1],df[i,2])}
>count
>1