Get all the rows with rownames starting with ABC111
You could use e.g. substr
or grepl
:
df <- read.table(header=TRUE, row.names=1, sep=" ", text="col1 col2 col3
ABC111001 12 12 13
ABC111002 3 4 5
ABC000111 7 6 1
ABC000112 9 23 1")
needle <- "ABC111"
i <- substr(row.names(df), 0, nchar(needle))==needle
i <- grepl(paste0("^", needle), row.names(df))
df[i,]
# col1 col2 col3
# ABC111001 12 12 13
# ABC111002 3 4 5
How can I apply dplyr's select(,starts_with()) on rows, not columns?
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")
How can i remove rows by condition (initial letters) in r?
You can also convert the data to a data frame and simply use filter()
by the dpylr
package. In addition to your code, you can have a solution like this:
Data <- data.frame(Data)
Then assign the filtered data to another dataframe.
DataFiltered <- Data %>% filter(Abbreviation %like% "SR_")
Similarly, you can use str_detect()
function from stringr
package for filtering. This works better, if there is a possibility that Abbreviation has entities having 'SR_' not only as the first 3 characters. You can use RegEx to specify that each entity in filtered data must have Abbreviation starting with 'SR_'.
DataFiltered <- Data %>% filter(str_detect(Abbreviation, pattern = "^SR_"))
R: converting tidyverse to dplyr/reshape2 for plots
Using only melt()
from reshape2
as suggested by great comment of @qdread and some base R
:
library(reshape2)
library(ggplot2)
#Code
Data$order <- rownames(Data)
Melted <- melt(Data,id.vars = c('order','ID','color'))
Melted$order <- as.numeric(Melted$order)
#Plot
G <- ggplot(Melted,aes(x = value,
y = order,
col = ID,
group = order)) +
# Draw points
geom_point()+
# Draw lines
geom_line() +
# Maybe you want to remove the y axis title, text and ticks
theme(axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
# I added a vertical format to the x axis labels
# it might easier to read this way
axis.text.x = element_text(angle = 90, vjust = 0.5))
Output:
Related Topics
Multiple Boxplots Using Ggplot
Change Size of Axes Title and Labels in Ggplot2
Replacing All Missing Values in R Data.Table with a Value
How to Add an Inset (Subplot) to "Topright" of an R Plot
How to Reference the Local Environment Within a Function, in R
Are Recursive Functions Used in R
Creating Legend with Circles Leaflet R
What Does the Double Percentage Sign (%%) Mean
Adding Legend to Ggplot When Lines Were Added Manually
R-Project Filepath from Concatenation
Print String and Variable Contents on the Same Line in R
How to Extract Fitted Splines from a Gam ('Mgcv::Gam')
How to Compute Roc and Auc Under Roc After Training Using Caret in R
How to Change the Resolution of a Raster Layer in R
Could Not Find Function Inside Foreach Loop