问题
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