How to extract rows from data frame with row names in R?
2
2
Entering edit mode
5.3 years ago

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 • 25k views
ADD COMMENT
2
Entering edit mode
5.3 years ago

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 COMMENT
2
Entering edit mode
5.3 years ago
Chirag Parsania ★ 2.0k

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 COMMENT

Login before adding your answer.

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