为什么R order函数在这个数据帧上不起作用——只返回第一个(未排序的)值



我有一个数据框架,其中包含以下列的调查结果:

 1) number of unanswered questions, 
 2) number of times the respondent answered with the most common (consensus) response, 
 3) number of questions answered, and 
 4) the percentage of questions in which the respondent answered with the consensus response.  

我想根据最后一列(一致答案的百分比)对其进行排序,并选择最高的五分之一。不过,我似乎无法分类。

这是str():

> str(consensus_participant_totals)
'data.frame':   210 obs. of  5 variables:
 $ V1           : Factor w/ 210 levels "R_06xJVSOuTuhYLOt",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ num_nas      : num  0 0 0 0 0 0 0 0 0 0 ...
 $ num_cons     : num  61 61 54 54 52 55 57 52 41 60 ...
 $ num_answered : num  68 68 68 68 68 68 68 68 68 68 ...
 $ pct_consensus: num  0.868 0.794 0.735 0.809 0.779 ...

以下是前几行:

consensus_participant_totals
                   V1 num_nas num_cons num_answered pct_consensus
1   R_06xJVSOuTuhYLOt       0       61           68     0.8676471
2   R_09aLjPFNmYMmsbX       0       61           68     0.7941176
3   R_0AphAH5kJRGOFfL       0       54           68     0.7352941
4   R_0cTBiuOmRWuFCZL       0       54           68     0.8088235
5   R_0dBEYzi8C7A65P7       0       52           68     0.7794118
6   R_0dCNkauEqyd2Y97       0       55           68     0.8529412

当我尝试时:

consensus_participant_totals[order(pct_consensus),]

我得到

Error in order(pct_consensus) : object 'pct_consensus' not found

这表明我必须引用它(在例子中似乎没有人这样做——我不明白为什么)

当我尝试使用引号时,我只得到第一行:

consensus_participant_totals[order("pct_consensus"),]             
                V1 num_nas num_cons num_answered pct_consensus
1 R_06xJVSOuTuhYLOt       0       61           68     0.8676471

我做错了什么?如何通过"pct_consensus"进行排序

谢谢你的指点!

您的问题是,如果不指定数据帧,就无法调用列。使用内置的数据示例(这既是为了让任何人都可以运行它,也是因为它的名称中的字符要少得多):

每个人都有iris数据集:

head(iris)

第一列是Sepal.Length,它在数据集中,但不在您的工作空间中,除非是数据集的一部分

head(iris$Sepal.Length)
head(iris[, "Sepal.Length"])
head(Sepal.Length) # error, no Sepal.Length

所以,当你根据一列进行排序时,你必须告诉R列在哪里

iris[order(iris$Sepal.Length), ]
iris[order(iris[, "Sepal.Length"]), ]
iris[order(iris["Sepal.Length"]), ]
with(iris, iris[order(Sepal.Length), ])

但不能忽视

iris[order(Sepal.Length), ]  # errors out

在解决这样的问题时,请记住,您可以运行R代码的微小片段。你说

> when I try it with quotes, I just get the first row:
consensus_participant_totals[order("pct_consensus"),]

这是因为您对长度为1的字符向量进行排序。如果你运行

order("pct_consensus")

它相当于这些

order("a")
order("whatever string you put here")

它们返回1,因为你问"如果我按字母顺序对一个字符串排序,它应该在哪个位置?"如果只有一个字符串,答案总是1。所以这就是你坐第一排的原因。

好吧,在玩了一番之后,它处理了以下内容:

c2 <-consensus_participant_totals[c(order(consensus_participant_totals[,"pct_consensus"])),]

我似乎可以把concat放在order函数之前或之后(例如,上面中的c(order(consensus_…或order(c(consensus

这看起来一点也不像大多数教程。我认为我的错误在于,大多数教程都使用了"attach"函数,这避免了在命令中输入数据帧名称,而我忽略了这一点。因此,简单地做(对于数据帧x)x[order(y),]是行不通的,因为我没有附加x.

我想。。。。

相关内容

最新更新