grep things and counting line number in R
2
2
Entering edit mode
6.6 years ago

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 • 8.1k views
ADD COMMENT
0
Entering edit mode

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 REPLY
0
Entering edit mode

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 REPLY
3
Entering edit mode
6.6 years ago
zx8754 12k

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 COMMENT
1
Entering edit mode
6.6 years ago

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 COMMENT
0
Entering edit mode

Hi,

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

ADD REPLY
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

Oh..thanks a lot .got it

ADD REPLY

Login before adding your answer.

Traffic: 1817 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6