Using R, I'm trying to search many csv files for columns that contain a specific folder name. The data files will always contain two column names PATIENT_ID, EVENT_NAME and then the actual data in many other columns.
The problem is that I don't know beforehand what the other column names are going to be. So there are many different column names and the output should be in a different structure.
So for example, the input file can be like this:
PATIENT_ID EVENT_NAME bp bpfile result
PAT_001 event_1 78 /files_dir/bp.pdf NEG
PAT_002 event_1 65 NA POS
PAT_003 event_1 71 /files_dir/document.pdf POS
PAT_004 event_2 82
PAT_005 event_2 79 /files_dir/bla.jpg /files_dir/report.pdf
And then I want to search all column that contain the phrase files_dir and create a new dataframe like this
PATIENT_ID EVENT_NAME var_name file_name
PAT_001 event_1 bpfile /files_dir/bp.pdf
PAT_003 event_1 bpfile /files_dir/document.pdf
PAT_005 event_2 bpfile /files_dir/bla.jpg
PAT_005 event_2 result /files_dir/report.pdf
So three bpfile values and one result value contain a filename.
Here is the code I've got so far:
# create newdata frame for output
df_output <- data.frame(matrix(ncol = 4, nrow = 0))
colnames(df_output) <- c("PATIENT_ID","EVENT_NAME","var_name","file_name")
# input data, test data
#mydata <- read.csv("patientct.csv", sep = ',', fileEncoding = 'UTF-8-BOM')
mydata <- data.frame(
PATIENT_ID = c('PAT_001', 'PAT_002', 'PAT_003', 'PAT_004', 'PAT_005'),
EVENT_NAME = c('event_1', 'event_1', 'event_1', 'event_2', 'event_2'),
bp = c(78, 65, 71, 82, 79),
bpfile = c('/files_dir/bp.pdf', NA, '/files_dir/documnet.pdf', '', '/files_dir/bla.jpg'),
result = c('NEG', 'POS', 'POS', '', '/files_dir/report.pdf')
)
# iterate all columns
for (colnam in colnames(mydata)) {
print(colnam)
if (!is.element(colnam, c("PATIENT_ID","EVENT_NAME")) )
{
# ???
count_file <- sum(grepl("files_dir", mydata[colnam]))
}
}
# output result
write.csv(df_output, "./outputfile_reslts.csv", row.names = TRUE)
I think there needs to be some pivot action, sort of. But I'm not that familiar with R, so I have no idea how to approach this. Any ideas?