Count number of characters in every row of a column
2
0
Entering edit mode
6.5 years ago
ioannis ▴ 50

Hi community,

I was wondering if anyone can give any advice on this:

> Chr = c("NC1", "NC2", "NC3")
> Pos = c(150, 165, 190)
> Seq = c("GATCGATGAC", "GATG", "ACGTAG")
> df = data.frame(Chr, Pos, Seq)

> df
Chr Pos        Seq
1 NC1 150 GATCGATGAC
2 NC2 165       GATG
3 NC3 190     ACGTAG

I want to count the characters of every row for the "Seq" Column and create a 4th column (let's call it NoCh) reporting the number of characters. First row GATCGATGAC is 10 characters. Second row GATG is 4 Third row ACGTAG is 6

Practically I want to do this:

> df
  Chr Pos        Seq NoCh
1 NC1 150 GATCGATGAC   10
2 NC2 165       GATG    4
3 NC3 190     ACGTAG    6

Any help would be much appreciated

Ioannis

R • 9.3k views
ADD COMMENT
1
Entering edit mode

Unless you're sure you want factors, create dataframes using data.frame(...,stringsAsFactors=FALSE). That, or use tidyverse and create a tibble.

ADD REPLY
0
Entering edit mode

Yes I will import my files into R using

read.table(..., stringsAsFactors=FALSE)

this will do the job. Thanks a lot Ram.

ADD REPLY
1
Entering edit mode
6.5 years ago
Ram 44k

You're looking for the functions apply and nchar. Search for a way to combine these two functions and you'll have your answer.

This is not strictly bioinformatics BTW :-)

ADD COMMENT
2
Entering edit mode
6.5 years ago
> df = data.frame(Chr, Pos, Seq, stringsAsFactors = FALSE)
> df$noChar <- nchar(df$Seq)
> df
  Chr Pos        Seq noChar
1 NC1 150 GATCGATGAC     10
2 NC2 165       GATG      4
3 NC3 190     ACGTAG      6
ADD COMMENT
0
Entering edit mode

Or that, yeah. I don't give code so people can try themselves and learn better.

ADD REPLY
0
Entering edit mode

When I can, I give code so that people see how it's done properly (or invite critique by other experts who will examine why my solution is not appropriate). I've learnt so much by reading other people's code (especially after futile attempts of my own) so I try to pass that on, especially if it's tiny snippets that won't cost me much of my own time. Just a different perspective

ADD REPLY
0
Entering edit mode

That’s a nice perspective! Cheers!

ADD REPLY
0
Entering edit mode

Yes exactly. Thanks a lot Friederike!

ADD REPLY

Login before adding your answer.

Traffic: 2294 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