对于数据框df
,我需要找到some_col
. 尝试了以下
length(unique(df["some_col"]))
但这并没有给出预期的结果。但是length(unique(some_vector))
适用于向量并给出预期的结果。
创建 df 时的一些前面的步骤
df <- read.csv(file, header=T)
typeof(df) #=> "list"
typeof(unique(df["some_col"])) #=> "list"
length(unique(df["some_col"])) #=> 1
Run Code Online (Sandbox Code Playgroud)
ros*_*ova 17
尝试使用[[
而不是[
. [
返回 a list
(data.frame
实际上是a ),[[
返回 a vector
。
df <- data.frame( some_col = c(1,2,3,4),
another_col = c(4,5,6,7) )
length(unique(df[["some_col"]]))
#[1] 4
class( df[["some_col"]] )
[1] "numeric"
class( df["some_col"] )
[1] "data.frame"
Run Code Online (Sandbox Code Playgroud)
您得到的值为 1,因为list
长度为 1(1 列),即使该 1 个元素包含多个值。
你需要使用
length(unique(unlist(df[c("some_col")])))
Run Code Online (Sandbox Code Playgroud)
当您通过 df[c("some_col")] 或 df["some_col"] 调用 column 时;它把它作为一个列表。Unlist 会将其转换为矢量,您可以轻松使用它。当您通过 df$some_col 调用 column .. 它将数据列拉为向量
我想你可能只是错过了一次,
尝试
length(unique(df[,"some_col"]))
Run Code Online (Sandbox Code Playgroud)
回复评论:
df <- data.frame(cbind(A=c(1:10),B=rep(c("A","B"),5)))
df["B"]
Run Code Online (Sandbox Code Playgroud)
输出 :
B
1 A
2 B
3 A
4 B
5 A
6 B
7 A
8 B
9 A
10 B
Run Code Online (Sandbox Code Playgroud)
和
length(unique(df[,"B"]))
Run Code Online (Sandbox Code Playgroud)
输出:
[1] 1
Run Code Online (Sandbox Code Playgroud)
这是与 OP 发布的相同的不正确/不需要的输出
但是用逗号 ,
df[,"B"]
Run Code Online (Sandbox Code Playgroud)
输出 :
[1] A B A B A B A B A B
Levels: A B
Run Code Online (Sandbox Code Playgroud)
和
length(unique(df[,"B"]))
Run Code Online (Sandbox Code Playgroud)
现在为您提供 OP 的正确/所需输出。在这个例子中是 2
[1] 2
Run Code Online (Sandbox Code Playgroud)
原因是df["some_col"]
调用 adata.frame
并length
调用对象类data.frame
会计算该对象中 data.frame 的数量,即 1,而df[,"some_col"]
返回 avector
并length
调用 avector
会正确返回该向量中的元素数量。所以你会看到一个逗号 ( ,
) 就产生了很大的不同。
归档时间: |
|
查看次数: |
47705 次 |
最近记录: |