[R] Extract an number from a character
Sam Albers
tonightsthenight at gmail.com
Mon Nov 23 21:20:53 CET 2015
Hello,
I have a problem to which I am certain grep or gsub or that family of
functions are the solution. However, I just can't seem to wrap my mind
around exactly how. I have a dataframe below that has the dimensions
of a net. I am given the data is the "W X H" format. For calculations
I'll like to have each number as a separated column. I have been using
ifelse(). However that seems like a poor solution to this problem
especially once dataframes get larger and larger.
So my question is, can anyone describe a way to extract the number
from the variable y below is the example? I had also tried substr()
but that fall apart with the 2.5 x 2.5 net.
Thanks in advance!
Sam
Example:
##dataframe
df<-data.frame(x=rnorm(10),
y=c("7 x 3","7 x 3","7 x 3","7 x 3","7 x 3","2.5 x
2.5","2.5 x 2.5","2.5 x 2.5","2.5 x 2.5","2.5 x 2.5"))
df$Width<-as.numeric(ifelse(df$y=="7 x 3","7","2.5"))
df$Height<-as.numeric(ifelse(df$y=="7 x 3","3","2.5"))
df$Width<-as.numeric(substr(df$y,5,5))
df$Width<-as.numeric(substr(df$y,5,5))
More information about the R-help
mailing list