根据逻辑条件过滤数据。

根据逻辑条件过滤数据。

我想从data.frame基于逻辑条件。假设我有数据框架,就像


   expr_value     cell_type

1    5.345618 bj fibroblast

2    5.195871 bj fibroblast

3    5.247274 bj fibroblast

4    5.929771          hesc

5    5.873096          hesc

6    5.665857          hesc

7    6.791656          hips

8    7.133673          hips

9    7.574058          hips

10   7.208041          hips

11   7.402100          hips

12   7.167792          hips

13   7.156971          hips

14   7.197543          hips

15   7.035404          hips

16   7.269474          hips

17   6.715059          hips

18   7.434339          hips

19   6.997586          hips

20   7.619770          hips

21   7.490749          hips

我想要的是获得一个新的数据框架,它看起来相同,但只有一个单元格类型的数据。例如:包含单元格类型“hESC”的子集/选择行:


   expr_value     cell_type

1    5.929771          hesc

2    5.873096          hesc

3    5.665857          hesc

或者细胞型“Bj成纤维细胞”或“hESC”:


   expr_value     cell_type

1    5.345618 bj fibroblast

2    5.195871 bj fibroblast

3    5.247274 bj fibroblast

4    5.929771          hesc

5    5.873096          hesc

6    5.665857          hesc

有什么简单的方法吗?


我试过:


expr[expr[2] == 'hesc']

# [1] "5.929771" "5.873096" "5.665857" "hesc"     "hesc"     "hesc"    

如果原始数据框架被称为“Exr”,但是它以错误的格式给出了结果,正如您所看到的。


达令说
浏览 686回答 3
3回答

至尊宝的传说

若要根据一“cell_type”(例如“hESC”),使用==:expr[expr$cell_type == "hesc", ]根据两个或多个不同的“cell_type”(例如,“hESC”)选择行或‘bj成纤维细胞’),使用%in%:expr[expr$cell_type %in% c("hesc", "bj fibroblast"), ]

哔哔one

使用subset(供互动使用)subset(expr, cell_type == "hesc")subset(expr, cell_type %in% c("bj fibroblast", "hesc"))或者更好dplyr::filter()filter(expr, cell_type %in% c("bj fibroblast", "hesc"))

陪伴而非守候

原因expr[expr[2] == 'hesc']对一个数据框架来说是行不通的,x[y]选择列,而不是行。如果要选择行,请更改为语法。x[y,]相反:> expr[expr[2] == 'hesc',]   expr_value cell_type4   5.929771      hesc5   5.873096      hesc6   5.665857      hesc
打开App,查看更多内容
随时随地看视频慕课网APP