I have a data called "test"
dput(test)>
structure(list(Data = c("Apple", "3", "Orange", "4", "Grape",
"2", "Orange", "5", "Grape", "1", "Orange", "4")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -12L))
I wish to extract the "Orange" number. How do I do that if all my data is in one column.
My desire output is
Data
Orange1
4
Orange2
5
Orange3
4
CodePudding user response:
With dplyr
library:
library(dplyr)
test%>% filter(Data == "Orange" | lag(Data)=="Orange")
Output:
# A tibble: 6 × 1
Data
<chr>
1 Orange
2 4
3 Orange
4 5
5 Orange
6 4
CodePudding user response:
Base R
test$Data[which(test$Data=="Orange") 1]
[1] "4" "5" "4"
CodePudding user response:
Here's a base R answer:
dat <- structure(list(Data = c("Apple", "3", "Orange", "4", "Grape",
"2", "Orange", "5", "Grape", "1", "Orange", "4")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -12L))
dat$Data[which(dat$Data == "Orange") 1]
#> [1] "4" "5" "4"
Created on 2022-10-19 by the reprex package (v2.0.1)