使用grep获取数据帧的行,而不是行号

时间:2017-07-22 01:00:51

标签: r dataframe grep

我正在尝试根据现有的数据框制作子数据帧。我的子数据帧正在填充行号而不是行本身。

rates = read.csv("file.txt")
genes = unique(gsub('_[0-9]+', '', rates[,1]))
for (k in unique(gsub('_[0-9]+', '', rates[,1])) ){
        sub = print(grep(k, rates[,1]), value=T)
        sub
}

file.txt的

clothing,freq,temp
coat_1,0.3,10
coat_1,0.9,0
coat_1,0.1,20
coat_2,0.5,20
coat_2,0.3,15
coat_2,0.1,5
scarf,0.4,30
scarf,0.2,20
scarf,0.1,10

这是当前的输出

[1] 1 2 3 4 5 6
[1] 7 8 9

我想要这样的东西

  clothing freq temp
1   coat_1  0.3   10
2   coat_1  0.9    0
3   coat_1  0.1   20
4   coat_2  0.5   20
5   coat_2  0.3   15
6   coat_2  0.1    5

  clothing freq temp
1    scarf  0.4   30
2    scarf  0.2   20
3    scarf  0.1   10

1 个答案:

答案 0 :(得分:1)

 rates <- read.csv("file.txt", stringsAsFactors = FALSE)
 rates
#  clothing freq temp
# 1   coat_1  0.3   10
# 2   coat_1  0.9    0
# 3   coat_1  0.1   20
# 4   coat_2  0.5   20
# 5   coat_2  0.3   15
# 6   coat_2  0.1    5
# 7    scarf  0.4   30
# 8    scarf  0.2   20
# 9    scarf  0.1   10

 rates[rates$clothing != "scarf",]
#  clothing freq temp
# 1   coat_1  0.3   10
# 2   coat_1  0.9    0
# 3   coat_1  0.1   20
# 4   coat_2  0.5   20
# 5   coat_2  0.3   15
# 6   coat_2  0.1    5
rates[rates$clothing == "scarf",]
#  clothing freq temp
#7    scarf  0.4   30
#8    scarf  0.2   20
#9    scarf  0.1   10