Question: How to extract rows from data frame with row names in R?
1
gravatar for blacktomato27
6 months ago by
United States
blacktomato2740 wrote:

Hi to all

I have CSV file with 11 columns and rows in it.

I read it into R as dataframe.

file1 <- read.csv("example-copy.csv", head = TRUE, sep =",",stringsAsFactors=F)

I want to extract rows with Names IND1 and IND3 with all the columns data. I tried with following code but i am not getting expected data and getting NA's.

Please found link to my example data here dropbox link to csv.

csv file

INDIVIDUAL,pop,M1,M2,M3,M4,M5,M6,M7,M8,M9
IND1,Aline,TT,CC,GG,GG,GG,CC,CC,TT,AA
IND2,Bline,TT,CC,GG,GG,GG,CC,AA,TT,AA
IND3,Rline,TT,GG,AA,GG,GG,TT,CC,CC,AA
IND4,Inbredline,TT,CC,AA,GG,GG,CC,CC,TT,AA
IND5,Bline,TT,CC,GG,GG,GG,CC,CC,TT,AA

expected results

INDIVIDUAL,pop,M1,M2,M3,M4,M5,M6,M7,M8,M9
IND1,Aline,TT,CC,GG,GG,GG,CC,CC,TT,AA
IND3,Rline,TT,GG,AA,GG,GG,TT,CC,CC,AA

and simple my code is here

file1 <- read.csv("reddy - Copy.csv", head = TRUE, sep =",",stringsAsFactors=F)
file2<-file1[c("IND1","IND3"),]
File2

I do not know where I went wrong in this code. Can any help me to solve this. any help in this regard will be highly appreciated

Thanks in advance

R • 1.1k views
ADD COMMENTlink modified 6 months ago by zx87547.8k • written 6 months ago by blacktomato2740
2
gravatar for Santosh Anand
6 months ago by
Santosh Anand4.9k
Santosh Anand4.9k wrote:

Although not a bioinformatics Q (purely R programming), I'll give a hint

There are various way to subset a data.frame in R. Look here and digest them all as they will be extremely useful for you in future

https://www.statmethods.net/management/subset.html

In particular, you may want to try

mySubset <- file1[ file1$INDIVIDUAL %in% c("IND1", "IND3"), ]
ADD COMMENTlink modified 6 months ago by zx87547.8k • written 6 months ago by Santosh Anand4.9k
2
gravatar for Chirag Parsania
6 months ago by
Chirag Parsania1.4k
University of Macau
Chirag Parsania1.4k wrote:

Solution given below. However, this is not bioinformatics question.

dd <- readr::read_delim("example - Copy.csv" , delim = ",")
out <- dd %>% dplyr::filter(INDIVIDUAL %in% c("IND" ,"IND1"))
out
# A tibble: 2 x 11
  INDIVIDUAL pop   M1    M2    M3    M4    M5    M6    M7    M8    M9   
  <chr>      <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 IND1       Aline TT    CC    GG    GG    GG    CC    CC    TT    AA   
2 IND1       Aline TT    CC    GG    GG    GG    CC    CC    TT    AA
ADD COMMENTlink modified 6 months ago • written 6 months ago by Chirag Parsania1.4k
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: 1687 users visited in the last hour