How can I apply dplyr's select(,starts_with()) on rows, not columns? [duplicate]

痞子三分冷 提交于 2021-01-16 01:04:47

问题


I'm now trying to figure out a way to select data having specific values in a variable, or specific letters, especially using similar algorithm that starts_with() does.

Say I have a data named "school" as below:

Name Math English
James 80   90
Tom   91   91
Shaun 99   71
Jack  92   91

here, select(school, starts_with("M")) gives me the column "Math" only. I want to apply this on rows, such as to command 'give me the rows where name starts with "J" letter', which will in turn give me a data with two rows.

I tried transposing the data and succeeded at what I wanted to get, but it's not what I really want though.

How can I do this work?


回答1:


I believe that the combination of dplyr's filter and the substring command are the most efficient:

library(dplyr)
filtered_df <- school %>% dplyr::filter(substr(Name,1,1) == "J")



回答2:


I think this will work:

library(tidyverse)
df <- df %>% filter(str_detect(Name, "^J"))


来源:https://stackoverflow.com/questions/43227088/how-can-i-apply-dplyrs-select-starts-with-on-rows-not-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!