Function to calculate CI of linear regression coefficients
Amateur code
```
jad<-function(x, y) {
model<-lm(y~x)
std.err<-coef(summary(model))[, 2]
coef.model1<-coef(summary(model))[, 1]
upper.ci<-coef.model1+1.96*std.err
lower.ci<-coef.model1-1.96*std.err
print(upper.ci)
print(lower.ci)
}
```
Pro code
jad <- function(x, y) {
`colnames<-`(
coef(summary(lm(y ~ x)))[,1:2] %*% matrix(c(1, 1.96, 1, -1.96), nrow = 2), c("upper.ci", "lower.ci")
)
}
Some data management Libraries for R
Library (magrittr)
Library (dplyr)
wrs%>%
extract(1:20,c("age", "edu")) %>%
head
or
wrs%>%
extract(1:20,1:2) %>%
head
Practical way to label factors
```
library(memisc)
labels(anemia$anem)<-c("not anemic"=0, "anemic"=1) #library memisc```
How to generate a simulated data in R
Package {simstudy}
The below example uses the library(simstudy) to generate a data of 10 observation for 3 variables: nr, x1 and y1. The function defData allows us to define the name, the formula and the distribution of each variable.
Check CRAN webiste for additional documentation on the simstudy package.
```
def <- defData(varname = "nr", dist = "nonrandom", formula = 7, id = "idnum")
def <- defData(def, varname = "x1", dist = "uniform", formula = "10;20")
def <- defData(def, varname = "y1", formula = "nr + x1 * 2", variance = 8)
dt <- genData(10, def)
dt
```
How to convert all characters of a data frame to Numeric
```
char_columns<-sapply(merged_data, is.character) #identify character columns
data_char_num<-merged_data #replicate data
data_char_num[,char_columns]<-as.data.frame(apply(data_char_num[,char_columns],2, as.numeric))#recode character as numeric
sapply(data_char_num, class) #print classes of all columns
```
How to make predictions from a linear model
Note: for numerical values you enter numbers without " ", for factor variables you enter the "label"
```
df<-data.frame(res=c("ModHigh"), age=c(21), sex=("female"), train=c("clinical"), bdi=c(4))
pred<-predict(adj.model6,df, data=resilience)
print(pred)
```
```
df<-data.frame(res=c("ModHigh"), age=c(21), sex=("female"), train=c("clinical"), bdi=c(4))
pred<-predict(adj.model6,df, data=resilience)
print(pred)
```
Subscribe to:
Posts (Atom)
Introduction to the Analysis of Survival Data in the Presence of Competing Risks
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4741409/
-
Sometimes when you are running a regression model with variables that have different lengths, r will prompt with the following error message...
-
In linear regression analysis, If the predictor X is the numerical variable "calories", then an increase of X from 10 to 30 will h...
-
Amateur code ``` jad<-function(x, y) { model<-lm(y~x) std.err<-coef(summary(model))[, 2] coef.model1<-coef(summary(model)...