Question: grep things and counting line number in R
2
gravatar for saadleeshehreen
11 months ago by
saadleeshehreen60 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 • 1.3k views
ADD COMMENTlink modified 11 months ago by zx87547.1k • written 11 months ago by saadleeshehreen60

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 11 months ago by h.mon24k

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 11 months ago • written 11 months ago by cpad011211k
2
gravatar for zx8754
11 months ago by
zx87547.1k
London
zx87547.1k 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 11 months ago by zx87547.1k
1
gravatar for Kevin Blighe
11 months ago by
Kevin Blighe41k
Guy's Hospital, London
Kevin Blighe41k 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 11 months ago • written 11 months ago by Kevin Blighe41k

Hi,

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

ADD REPLYlink written 11 months ago by saadleeshehreen60

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

ADD REPLYlink written 11 months ago by Kevin Blighe41k

Oh..thanks a lot .got it

ADD REPLYlink written 11 months ago by saadleeshehreen60
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: 1397 users visited in the last hour