R中的向量而不是数据帧上的dplyr过滤器 [英] dplyr filter on a vector rather than a dataframe in R

查看:48
本文介绍了R中的向量而不是数据帧上的dplyr过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个简单的问题,但是我还没有找到一个干净的解决方案.我在R中有一个向量,并且想从向量中删除某些元素,但是出于各种原因,我想避免使用vector [vector!="thiselement"]表示法.特别是,这是我要尝试做的事情:

This seems like a simple question, but I have not come across a clean solution for it yet. I have a vector in R and I want to remove certain elements from the vector, however I want to avoid the vector[vector != "thiselement"] notation for a variety of reasons. In particular, here is what I am trying to do:

# this doesnt work
all_states = gsub(" ", "-", tolower(state.name)) %>% filter("alaska")

# this doesnt work either
all_states = gsub(" ", "-", tolower(state.name)) %>% filter(!= "alaska")

# this does work but i want to avoid this approach to filtering
all_states = gsub(" ", "-", tolower(state.name))
all_states = all_states[all_states != "alaska"]

这可以通过简单的方式完成吗?预先感谢您的帮助!

can this be done in a simple manner? Thanks in advance for the help!

编辑-我为此苦苦挣扎的原因是因为我只在网上找到有关基于数据帧的列进行过滤的内容,例如:

EDIT - the reason I'm struggling with this is because I'm only finding things online regarding filtering based on a column of a dataframe, for example:

my_df %>% filter(col != "alaska")

但是我在这里使用向量而不是数据帧

however I'm working with a vector not a dataframe here

推荐答案

可以肯定dplyr仅对data.frames有效.这是一个两行示例,将向量强制转换为data.frame然后返回.

Pretty sure dplyr only really operates on data.frames. Here's a two line example coercing the vector to a data.frame and back.

myDf = data.frame(states = gsub(" ", "-", tolower(state.name))) %>% filter(states != "alaska")
all_states = myDf$states

或一毛的班轮:

all_states = (data.frame(states = gsub(" ", "-", tolower(state.name))) %>% filter(states != "alaska"))$states

这篇关于R中的向量而不是数据帧上的dplyr过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆