I am importing a key in which each row is an argument setting for a function I have programmed. The goal is to batch test my function by producing outputs for all sets of arguments. That's not terribly important. What is important is that I import a column that contains in each row a value for a range. For instance, "1:5" is meant to be entered into an argument as the value 1:5. I try to coerce using as.numeric("1:5"), but R is not happy with this. Is there a way to coerce this to the string c(1,2,3,4,5) from the character value "1:5"
Asked
Active
Viewed 59 times
1
-
@Richard Scriven re:duplicate question. This seems different than the title of the question stated in this former string if not the actual question therein itself. I am not turning a general character string into a numeric value since this actually cannot be coerced from character to value using as.numeric. I probably missed the other one for this reason since its title makes it relatively indistinguishable from a much simpler case that I could have done. All the same, thanks for letting us know. – Eich Sep 03 '15 at 00:12
-
I reopened it. I was just going off the question you wrote *Is there a way to coerce this to the string c(1,2,3,4,5) from the character value "1:5"*, which is the same thing as in the linked question. Sorry for the confusion – Rich Scriven Sep 03 '15 at 00:15
2 Answers
2
Reduce(':', strsplit(x,":")[[1]])
[1] 1 2 3 4 5
If x = "1:5"
, we can use strsplit
to separate the two numbers. We can then use Reduce
to execute the operator :
on the split.

Pierre L
- 28,203
- 6
- 47
- 69
2
Your text is valid code, so you can eval(parse
it
dat$parsed <- lapply(dat$key, function(x) eval(parse(text=x)))
# key parsed
# 1 1:5 1, 2, 3, 4, 5
# 2 1:6 1, 2, 3, 4, 5, 6
# 3 1:4 1, 2, 3, 4
Data
dat <- read.table(text="key
1:5
1:6
1:4", strings=F, header=T)

Rorschach
- 31,301
- 5
- 78
- 129
-
No worries - in this case `sapply` will actually fail if for instance `dat$key` is `c("1"3","2:4")` as it will try to fit 3 rows in two rows because of the simplifying to array. Granted, this is a very unusual circumstance. – thelatemail Sep 02 '15 at 23:44
-
@nongkrong, this is the answer I am looking for. I am still new enough to R that I haven't encountered parse before, but this works. I had to go through it to see why eval was necessary, but I get the string now. Thank you for your help! – Eich Sep 03 '15 at 00:10
-
`dat <- data.frame(key=c("1:3","2:4"),stringsAsFactors=FALSE)` and then `dat$parsed <- sapply(dat$key, function(x) eval(parse(text=x)))` will fail. – thelatemail Sep 03 '15 at 00:10
-
@thelatemail good point, so it's when all the expansions are the same length – Rorschach Sep 03 '15 at 00:15