我试图查看数据框中按数值排序的所有精确值。令我惊讶的是,“unique”命令并未显示所有唯一值。我的想法是,也许有一个子命令 unique 之类的,但我找不到任何东西。这段代码说明了我尝试做的事情以及我期望的输出。
d <- data.frame(
crp = as.numeric(c("1.0001","1","0.999999999", "0.999999999")),
crp.txt = as.integer(c("1.0001","1","0.999999999", "0.999999999"))
)
sort(unique(d$crp)) # is sorted but doesn't show exact values
sort(unique(toString(d$crp))) # is not sorted but shows all values
sort(unique(d$crp.txt)) # is sorted but doesn't show exact values
sort(unique(toString(d$crp.txt))) # is not sorted and doesn't show exact values
# expected output: [1] "0.999999999, 1, 1.0001"
我做错了什么/我应该采取不同的做法吗?
我认为问题在于,当您使用 toString() 将列转换为字符串时,您将整个列转换为单个字符串,这不是您想要的。相反,您应该使用 as.character() 将列的每个元素单独转换为字符串。这里有一个替代方案:
sort(unique(unlist(d)))
[1] "0.999999999" "1" "1.0001"
此外,如果您想使用您的代码,您可以执行以下操作:
# Convert each element of d$crp to character and then get unique values
unique(as.character(d$crp))
# Sort the unique values
sort(unique_crp)
# Convert each element of d$crp.txt to character and then get unique values
unique(as.character(d$crp.txt))
# Sort the unique values
sort(unique_crp_txt)