[R] converting values of a dataframe to numeric (where possible)
Ralikwen
Balazs.Klein at gmail.com
Tue Sep 2 23:50:16 CEST 2008
Hi,
I am new to R.
I have a dataframe with many columns some of which contain genuine strings
some numerical values as strings. The dataframe is created by cast so I have
no control over the resulting data type.
I want to attach columns as aggregates of other columns to the dataframe.
Here is the solution that I came up with (after a lot of struggle):
castNum <- function(n) {
x<-as.numeric(as.character(n))
if (is.na(x)){
return(n)
}else{
return(x)
}
}
df <- data.frame(a=letters[15:17], b=c("21","NA","23"), c=10:12, d=15:17)
cbind(df,RTot=rowSums(as.data.frame(lapply(df, function(x)
castNum(x)))[2:4],na.rm=TRUE))
This works, but is full of warnings and looks extremely ugly.
Could you direct me how to achieve the same result in a more elegant way?
Thx.
Balázs
--
View this message in context: http://www.nabble.com/converting-values-of-a-dataframe-to-numeric-%28where-possible%29-tp19279139p19279139.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list