vardha
vardha

Reputation: 414

find occurrence of string starting with a value in R

Is there a function for printing the total number of values contained in the dataset beginning with (a value)?

consider this dataset of 4 version numbers,

df <- c("1.20", "3.1.20", "2.45", "1.10", "1.67.4.3", "5.200.1", "70.1.2.7")

I need to only print version numbers 1.x. My output would be:

1.20, 1.10, 1.67.4.3

(becasue these are version numbers starting with "1." I do not want to print 3.1.20 or 70.1.2.7 becasue they do not start with "1." eventhough they contain "1." as a substring

Upvotes: 3

Views: 4859

Answers (4)

RHertel
RHertel

Reputation: 23798

df[df<"2"]
#[1] "1.20"     "1.10"     "1.67.4.3"

Depending on your dataset (e.g., if there are version numbers with a leading zero), you might need to expand this suggested solution by df[df<"2" & df>="1"]

The total number of values starting with a "1" can in this case be obtained with length(df[df<"2"]) (or length(df[df<"2" & df >="1"]) ).

Upvotes: 0

Pierre L
Pierre L

Reputation: 28451

Or:

sum(substr(df, 1, 2) == "1.")
[1] 3

And for the values themselves:

df[substr(df, 1, 2) == "1."]
[1] "1.20"     "1.10"     "1.67.4.3"

Upvotes: 0

Andrelrms
Andrelrms

Reputation: 819

df <- c("1.20", "3.1.20", "2.45", "1.10", "1.67.4.3", "5.200.1", "70.1.2.7")
grep("^1\\.", df, value = TRUE)

Upvotes: 8

Paulo MiraMor
Paulo MiraMor

Reputation: 1610

Use the function substring inside brackets for subsetting:

df[substring(df, 1,2) == "1."]

Upvotes: 0

Related Questions