Subset data frames stored inside a list in R by same column name
1
1
Entering edit mode
6.1 years ago
paolo002 ▴ 160

Hi all

I have multiple csv files stored in a list (list.data) having same column names but different data frame names. I would like to subset a column (CHR) by a specific value (1) and apply it to all the data frames in the list and to all the columns.

I wrote this code :

CHR1<-lapply(list.data, function(x) { x["CHR"] = 1; x }

However this seem to subset correctly that specific column (CHR) but the other columns did not change, subset was not applied to the rest of the columns.

I wrote also this code but it returns an empty list

CHR1<-lapply(list.data, subset, "CHR"=1)

Any help highly appreciated. Thanks

R subset • 3.9k views
ADD COMMENT
1
Entering edit mode
6.1 years ago
zx8754 12k

Try:

CHR1 <- lapply(list.data, function(x) { x[ x$CHR == 1, ] })
  • = is an assignment operator, e.g.: myVar = 1; print(myVar) same as <-.

  • == is a logical operator, used for comparing, e.g.: 1 == 2 this will give us FALSE.

ADD COMMENT
0
Entering edit mode

Thank you very much for your help once again. It worked. And thanks for the explanation.

ADD REPLY

Login before adding your answer.

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