R - 子集数据帧仅保留与所有列上的多个条件一致的行

时间:2017-07-18 19:26:49

标签: r csv filter subset grepl

我想要的快速摘要是:

我在同一文件夹中有数千个.csv文件,其中包含折扣率贴现现金流等短语,主要在第一列,但也随机在前10列。

使用某些功能(可能是grepl()subset()filter()),我想提取包含这些短语的行并将它们放入新的数据框中以及他们每个人来自的文件的名称。

我遇到的问题是,我一直在尝试的每个功能只允许一次查看一列或两列。这是我一直在使用的代码:

#Reading in a single .csv file for now:
MyData <- read.csv("c:/____________/.csv", header = TRUE, sep=",")

#Assigning numbers to each column since each file I will be plugging in has different column headings:
colnames(MyData) <- c(1:ncol(MyData))

#Using subset to check the 1st column and 5th column for discount rate 
#(only because I knew these 2 columns contained the phrase "discount rate" ahead of time.)
my.data.frame <- subset(MyData, MyData$`1`=="discount rate" | MyData$`5`=="discount rate")

所以,重申一下,我想知道是否有办法搜索许多短语,例如折扣率折扣率贴现现金流量在某些data.frame中的每一列上。感谢您提供的任何帮助。

此外,我提供的代码确实返回包含指定列的行 折扣率,但不包含折扣率等其他字词的行数为5.0%。如果知道这个问题的解决方案,那么我将非常感激。

picture of the code I have been working with

Results from my code in a data frame

3 个答案:

答案 0 :(得分:0)

这样的事情会起作用吗?您可以使用正则表达式(regex)修改 根据您的需要“折扣”。

#Sample dataframe with 'discount rate', 'discounted rates', or 'discounted cash flow' randomly placed
df <- data.frame(a=c('discount rate', 'nothing', 'discounted cash flow', 'nothing', 'nothing'), b=1:5,
  c=6:10, d=c('nothing', 'discounted rates', 'nothing', 'nothing', 'nothing'), stringsAsFactors = F)
df
                     a b  c                d
1        discount rate 1  6          nothing
2              nothing 2  7 discounted rates
3 discounted cash flow 3  8          nothing
4              nothing 4  9          nothing
5              nothing 5 10          nothing

#Get rows where the word 'discount' occurs in any row
discountRows <- unique(unlist(apply(df, 2, function(x) grep('discount', x))))

#Subset df with only rows where the word 'discount' occurs
df[discountRows,]
                     a b c                d
1        discount rate 1 6          nothing
3 discounted cash flow 3 8          nothing
2              nothing 2 7 discounted rates

#Assign subsetted df to new dataframe with original name in it
assign(paste0(deparse(substitute(df)), '_discountRows'), df[discountRows,])

答案 1 :(得分:0)

考虑使用位于grepl内的TRUE/FALSE(在正则表达式匹配上返回apply)。并将所有包装在一个更大的lapply中,通过包含子集化行的许多csv文件构建一个数据帧列表,然后在结束时将所有行绑定:

setwd("C:/path/to/my/folder")
myfiles <- list.files(path="C:/path/to/my/folder")

dfList <- lapply(myfiles, function(file){
    df <- read.csv(file, header = TRUE)
    colnames(df) <- c(1:ncol(df))

    # ADD COLUMN FOR FILENAME
    df$filename <- file

    # RETURNS 1 IF ANY COLUMN HAS MATCH
    df$discountfound <- apply(df, 1, function(col) 
                              max(grepl("discount rate|discounted cash flow", col)))

    # SUBSET AND REMOVE discountfound COLUMN
    df <- transform(subset(df, df$discountfound == TRUE), discountfound=NULL)
})

# ASSUMES ALL DATAFRAMES HAVE EQUAL NUMBER OF COLUMNS
finaldf <- do.call(rbind, dfList)

答案 2 :(得分:0)

你可以试试这个。我希望这就是你想要的。

mydata = data.frame(a = c(1:3,"discount rate","discounted rates",2:5),
                    b = c("discount rate","discounted rates",2:8))

row = c()
for (i in 1:nrow(mydata)){
  good_row = grep(paste("discount rate","discounted rates",sep="|"),unlist(mydata[i,]))
  if (length(good_row) != 0){
    row = c(row,i)
  }
}

mydata = mydata[row,]