Question: Count number of characters in every row of a column
0
gravatar for ioannis
3 months ago by
ioannis20
ioannis20 wrote:

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 • 147 views
ADD COMMENTlink modified 3 months ago by Ram17k • written 3 months ago by ioannis20
1

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

ADD REPLYlink written 3 months ago by Ram17k

Yes I will import my files into R using

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

this will do the job. Thanks a lot Ram.

ADD REPLYlink written 3 months ago by ioannis20
1
gravatar for Ram
3 months ago by
Ram17k
Houston, TX
Ram17k wrote:

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 COMMENTlink written 3 months ago by Ram17k
2
gravatar for Friederike
3 months ago by
Friederike2.0k
United States
Friederike2.0k wrote:
> 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 COMMENTlink written 3 months ago by Friederike2.0k

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

ADD REPLYlink written 3 months ago by Ram17k

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 REPLYlink written 3 months ago by Friederike2.0k

That’s a nice perspective! Cheers!

ADD REPLYlink written 3 months ago by Ram17k

Yes exactly. Thanks a lot Friederike!

ADD REPLYlink written 3 months ago by ioannis20
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: 1497 users visited in the last hour