【问题标题】:selected rows from the column as per the values in the rows [duplicate]根据行中的值从列中选择行[重复]
【发布时间】:2019-02-25 17:21:12
【问题描述】:

我有一个 df 如下:其中有 2 列,学生姓名和分数。

Stud_name   Marks
Jon         25
john        20
ajay        50
ram         27
jay         61
jess        46
troy        23
mike        42
steve       45
glenn       43

我想要几个名字和他们的标记。

预期输出:

Stud_name   Marks
john        20
ajay        50
jess        46
troy        23
ram         27
glenn       43

请帮忙。

我试过了:

pd <- filter(df,Stud_name == "john" , "ajay" , "jess")

Error in filter_impl(.df, quo) : 
Evaluation error: operations are possible only for numeric, logical or 
    complex types.

【问题讨论】:

  • 选择背后的逻辑是什么?
  • 程序应该如何决定返回哪些行,这与您当前获得的输出有何不同?还有你目前使用的是什么代码?
  • 没有逻辑只需要按照预期输出的列中的名称获取名称和标记。
  • “几个名字”作为数据样本,使用sample()?
  • 使用%in%而不是==,即filter(df, Stud_name %in% c("john" , "ajay" , "jess"))

标签: r dplyr


【解决方案1】:

如果您可以考虑使用基本解决方案,您可以试试这个:

# your data
dats <- read.table(text='Stud_name   Marks
Jon         25
                   john        20
                   ajay        50
                   ram         27
                   jay         61
                   jess        46
                   troy        23
                   mike        42
                   steve       45
                   glenn       43',sep='', header=T)

# vector with choosen names
names <- c("john","ajay","jess")
dats[which(dats$Stud_name %in% names),]

或者(感谢@markus):

dats[(dats$Stud_name %in% names),]
  Stud_name Marks
2      john    20
3      ajay    50
6      jess    46

【讨论】:

  • 问题是关于 dplyr::filter 错误,而不是关于“给我展示替代方案”。
  • 是的,没有它。谢谢s_t
  • 哦,我知道OP尝试的是dplyr::filter,这不是强制性的。我会编辑答案,谢谢。
  • 是的,我正在使用 dplyr。谢谢。
猜你喜欢
  • 2014-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-22
  • 2016-07-24
  • 2016-06-23
  • 2017-06-17
  • 1970-01-01
相关资源
最近更新 更多