Reputation: 53
I have created a spreadsheet in Excel with concatenate
in order to make things easier for later use. Now I want to evaluate the text strings. Doing it in Excel sounds harder than doing it in R. Therefore, I was wondering how to import and evaluate in R. Instead of what I want, I get text strings like the following.
Air.Force.Falcons Akron.Zips Alabama.Crimson.Tide
1 -.8*2-(1-.8)*1 -.5*0+(0)*(2*.8-1)/2 -.5*0+(0)*(2*.8-1)/2
2 -.5*0+(0)*(2*.8-1)/2 -.8*2-(1-.8)*1 -.5*0+(0)*(2*.8-1)/2
3 -.5*0+(0)*(2*.8-1)/2 -.5*0+(0)*(2*.8-1)/2 -.8*0-(1-.8)*2
4 -.5*0+(0)*(2*.8-1)/2 -.5*0+(0)*(2*.8-1)/2 -.5*0+(0)*(2*.8-1)/2
5 -.5*0+(0)*(2*.8-1)/2 -.5*0+(0)*(2*.8-1)/2 -.5*0+(0)*(2*.8-1)/2
6 -.5*0+(0)*(2*.8-1)/2 -.5*0+(0)*(2*.8-1)/2 -.5*0+(0)*(2*.8-1)/2
7 -.5*0+(0)*(2*.8-1)/2 -.5*0+(0)*(2*.8-1)/2 -.5*0+(0)*(2*.8-1)/2
How do I import them as numeric or evaluate them as numeric after the fact? I've tried as.numeric
and colClasses="numeric"
. To recreate this, simply make a spreadsheet with formulas like =concatenate("-5*3")
. How do I reverse this? Thanks.
Link to output of dput(head(week15_90))
https://docs.google.com/document/d/1xCVjSff6f055PX8qEnVLh49V6TYXFQeZZzc3bofG5z4/edit?usp=sharing
Upvotes: 3
Views: 232
Reputation: 121568
Faster to unlist first your data (put it as a vector), and apply the classical eval(parse(text=))
matrix(lapply(unlist(dat),
function(y)eval(parse(text=y))),ncol=ncol(dat))
Example:
dat <- data.frame( x=rep("-x+1",2) ,y =rep("x^2",2),stringsAsFactors=F)
> dat
x y
1 -x+1 x^2
2 -x+1 x^2
x <- 0.2
matrix(lapply(unlist(dat),function(y)
eval(parse(text=y))),ncol=ncol(dat))
[,1] [,2]
[1,] 0.8 0.04
[2,] 0.8 0.04
Upvotes: 3
Reputation: 6355
data.frame(lapply(df, function(y) sapply(y, function(x) eval(parse(text=x)))))
should do it.
Make sure the elements of the data frame df are strings and not factors - if they are factors you will have to convert them.
Upvotes: 2