BeccaLi
BeccaLi

Reputation: 184

R: Convert summary()$coef into numeric vector

I am trying to use a standard curve (regression line) to analyse my data. The standard curve looks similar to this:

 myData <- data.frame(x=rep(c(10,1,0.1,0.01),each=3),
                          y=(c(26, 25, 24.5,2.65,2.4,2.5,
                               0.25,0.245,0.265, 0.025,0.027,0.024)))

When I use the function lm() to get the line of regression and then coef to receive the coefficients, this works fine. However when I try to convert the output to a numeric vector that I can reuse in my later code, the values change from what they are to 1 and 2. What did I do wrong? Thanks for any help!

xy <- lm(y~x, data=myData) #Intercept(y) = 0.000653277183897452; x = 2.51659647986179 
datOut <- summary(xy)$coef
PPL <- cbind(VariableName=rownames(datOut), datOut)

ppl<-as.data.frame(PPL)
#Results look great

ppl$Estimate<-as.numeric(ppl$Estimate)
#Estimate column content changes to 1 and 2

Upvotes: 0

Views: 1204

Answers (2)

cyrilb38
cyrilb38

Reputation: 944

ppl$Estimate is initially a factor. If you convert it directly to numeric, it will provide the level of the factor (hence the 1, 2...). You have first to convert it to character :

ppl$Estimate<-as.numeric(as.character(ppl$Estimate))

Or as 27 ϕ 9 mentions, use stringsAsFactors = FALSE when initializing your dataframe.

Upvotes: 1

Roland
Roland

Reputation: 132706

Never, ever use cbind followed by as.data.frame. cbind changes the data types because it creates a matrix and a matrix can only contain one data type. Just use data.frame and you won't need to "fix" the data types afterwards:

set.seed(42)
xy <- lm(y~x, data=data.frame(x = rnorm(10), y = rnorm(10))) 
datOut <- summary(xy)$coef

ppl <- data.frame(VariableName=rownames(datOut), datOut)
str(ppl)
#'data.frame':  2 obs. of  5 variables:
#$ VariableName: chr  "(Intercept)" "x"
#$ Estimate    : num  0.237 -0.732
#$ Std..Error  : num  0.616 0.64
#$ t.value     : num  0.385 -1.144
#$ Pr...t..    : num  0.71 0.286

Upvotes: 0

Related Questions