问题
I have this piece of code that is in need of some streamlining:
SlopeSBS00<-lm(SBSNy$SBS00[c(1:10,17:41)] ~ Numbers[c(1:10,17:41)])$coeff[2]
SlopeSBS01<-lm(SBSNy$SBS01[c(1:10,17:41)] ~ Numbers[c(1:10,17:41)])$coeff[2]
SlopeSBS02<-lm(SBSNy$SBS02[c(1:10,17:41)] ~ Numbers[c(1:10,17:41)])$coeff[2]
SlopeSBS03<-lm(SBSNy$SBS03[c(1:10,17:41)] ~ Numbers[c(1:10,17:41)])$coeff[2]
...
SlopeSBS23<-lm(SBSNy$SBS23[c(1:10,17:41)] ~ Numbers[c(1:10,17:41)])$coeff[2]
Here SBSNy is a transformed version of a variable SBS, which is normalized, and Numbers is a numbers vector from 1:41. So basically what this code does for each line is doing a linear regression of SBSNy for each SBS00 to SBS23, for the columns 1:10 and 17:41. Coeff[2] only exports the Slope which is needed here.
I forgot to add something
The SlopeSBS00 to SlopeSBS23 needs to be combined into a data.frame: something like this: SlopeSBS <-data.frame(SlopeSBS00,SlopeSBS01,...,SlopeSBS23)
Much appreciated any form of guidance or help with this piece of code
Data example
SBSNy contains a data.frame with 41 observations and 25 variables:
Numbers SBS00 SBS01 SBS02 ... SBS23
1 1.600 1.735 1.644 ... 1.328
2 1.486 1.692 1.522 ... 1.301
3 1.421 1.597 1.370 ... 1.321
... ... ... ... ... ...
41 1.286 1.395 1.182 ... 1.206
An example on a code to manufacture the data, although this data is with a range from 0-100:
df1 <- as.data.frame(matrix(sample(0:100,24*41,replace=TRUE),nrow=41, ncol=24))
Numbers <-c(1:41)
SBSNy<-data.frame(Numbers,df1)
names(SBSNy)<-c("Numbers",sprintf('SBS%02d',0:23))
回答1:
Assuming that "SBS00" is your secont column on your data frame "SBSNy":
for (x in 1:23){
if (x < 10){
var <- paste0("SBS0", x)
} else {
var <- paste0("SBS", x)
}
assign(paste0("Slope", var), lm(SBSNy[c(1:10,17:41), x+1] ~ Numbers[c(1:10,17:41)])$coeff[2])
}
# Untested code
来源:https://stackoverflow.com/questions/31182761/code-cleanup-in-r