Rscript test.R ../Data/bam/a.bam:0 ../Data/bam/b.bam:0.1 ../Data/bam/c.bam:0.5 ../Data/bam/d.bam:1
I want to make a list of keys and values for commandline arguments. I have use following code.
#test.R
args <- commandArgs(trailingOnly = TRUE)
key_value_pairs <- strsplit(args, " ")
key_value_pairs <- lapply(key_value_pairs, function(x) strsplit(basename(x), ":")[[1]])
key_value_pairs <- as.data.frame(key_value_pairs, stringsAsFactors = FALSE)
colnames(key_value_pairs) <- c("key", "value")
key_value_pairs$value <- as.numeric(key_value_pairs$value)
print(key_value_pairs)
i got follwoing output:
key value
1 a.bam NA
2 0
NA
1 b.bam
2 0.1
NA
1 c.bam
2 0.5
NA
1 d.bam
2 1
NA
but i want out like:
key value
a.bam 0.0
b.bam 0.1
c.bam 0.5
d.bam 1
Can someone help me to find the issue and how to solve it. Thanks
#test.R
args <- commandArgs(trailingOnly = TRUE)
key_value_pairs <- strsplit(args, " ")
key_value_pairs <- lapply(key_value_pairs, function(x) strsplit(basename(x), ":")[[1]])
key_value_pairs <- as.data.frame(key_value_pairs, stringsAsFactors = FALSE)
colnames(key_value_pairs) <- c("key", "value")
key_value_pairs$value <- as.numeric(key_value_pairs$value)
print(key_value_pairs)
CodePudding user response:
Note that the command args are already separated by space so you don't need to do that yourself. And you need a different strategy for creating your data.frame. This should work
args <- commandArgs(trailingOnly = TRUE)
key_value_pairs <- lapply(args, function(x) strsplit(basename(x), ":")[[1]])
key_value_pairs <- as.data.frame(do.call("rbind", key_value_pairs), stringsAsFactors = FALSE)
colnames(key_value_pairs) <- c("key", "value")
key_value_pairs$value <- as.numeric(key_value_pairs$value)
key_value_pairs
# key value
# 1 a.bam 0.0
# 2 b.bam 0.1
# 3 c.bam 0.5
# 4 d.bam 1.0
An alternate way to do this would be
args <- commandArgs(trailingOnly = TRUE)
key_value_pairs <- read.table(text=basename(args), sep=":",
col.names = c("key", "value"))
That will pretty much do everything in one go.