Question: grep things and counting line number in R
2
gravatar for saadleeshehreen
2.4 years ago by
saadleeshehreen70 wrote:

Hi, I am a beginner in R. I want to grep "x" from file1 and pipe it with line count command to know how many lines in file1 contain "X". What is the command for it?

R • 3.5k views
ADD COMMENTlink modified 2.4 years ago by zx87549.6k • written 2.4 years ago by saadleeshehreen70

Why do you need to do this in R, if there are many (bash + grep, perl, python; to name just three) better tools for the task?

ADD REPLYlink written 2.4 years ago by h.mon31k

I understand that OP wants grep and wc functions in R for "x". IMO, this is kind of looking for duplicates i.e count the lines where X is present more than once. This function might do that: (Assumption is that X is present once in a line and X is not part of a string).

length(df[df=="x"])
ADD REPLYlink modified 2.4 years ago • written 2.4 years ago by cpad011214k
2
gravatar for zx8754
2.4 years ago by
zx87549.6k
London
zx87549.6k wrote:

Let's say we have below file:

file1.txt

texst1  test1
test2   test1
test3   test1
test4   xtexst1
test5x  test1

We can read the file, and use grepl to search for "x". grepl returns TRUE for matches, then we can sum to get the count.

myFile <- readLines("file1.txt")
sum(grepl(pattern = "x", x = myFile))
# [1] 3
ADD COMMENTlink written 2.4 years ago by zx87549.6k
1
gravatar for Kevin Blighe
2.4 years ago by
Kevin Blighe65k
Kevin Blighe65k wrote:

Shell / BASH:

cat test
echo on
hello world
hello world
alo mundo
alo mundo
hola mundo
hola mundo
echo off

Then, load R:

R

system("grep -e 'hello' test | wc -l")
2

system("grep -e 'echo' test | wc -l")
2

system("grep -e 'echo' test")
echo on
echo off

system("grep -e 'mundo' test | wc -l")
4

system("grep -e 'mundo' test")
alo mundo
alo mundo
hola mundo
hola mundo

system() allows you to invoke operating system commands.

You can also read the file into R but it would help if it were TSV or CSV, an there run the grep() R command.

Kevin

ADD COMMENTlink modified 2.4 years ago • written 2.4 years ago by Kevin Blighe65k

Hi,

I was looking for a command in R. I know 'grep' and 'wc -l' work in shell.

ADD REPLYlink written 2.4 years ago by saadleeshehreen70

Please re-read my answer. The system() function in R allows you to do what you want.

ADD REPLYlink written 2.4 years ago by Kevin Blighe65k

Oh..thanks a lot .got it

ADD REPLYlink written 2.4 years ago by saadleeshehreen70
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1755 users visited in the last hour