根据因素(字符串)从R数据框中提取行 [英] Extract rows from R data frame based on factors (strings)

查看:53
本文介绍了根据因素(字符串)从R数据框中提取行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这是重复的,尽管看起来像是一个简单的问题,但我似乎无法在SO的其他任何地方找到该信息.我有一个包含几列的数据框.其中一些是整数,有些是字符串.我想提取与特定因素相对应的行.例如

Sorry if this is a duplicate, but I can't seem to find the information anywhere else on SO, even though it seems like such a simple problem. I have a data frame with several columns as factors. Some of those are integers, and some are strings. I would like to extract the rows that correspond to a particular factor. For example,

my_data <- read.table(file = "my_data.txt", header = TRUE)
my_data[ my_data$age == 20, ]

这有效,但是如果我再尝试

This works, but if I then try

my_data[ my_data$gender == "male", ]

这没有匹配项.我意识到它们不是一回事,因为在对字符串进行检查时,检查 my_data $ name [1] 的类给出了因素.

This produces no matches. I realized they are not the same thing, as checking the class of my_data$name[1] gives factor, while I'm checking it against a string.

有什么想法我在这里做错了吗?

Any ideas what I'm doing wrong here?

欢呼

数据样本:大小年龄性别价值1 20男0.54 22女0.73 14女0.3

Data sample: Size Age Gender Value 1 20 male 0.5 4 22 female 0.7 3 14 female 0.3

推荐答案

尝试使用 subset 函数.

此站点提供了很好的参考: HowtoInR

This site provides a good reference: HowtoInR

my_data = subset(my_data, gender == "male")

这篇关于根据因素(字符串)从R数据框中提取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆