Beruflich Dokumente
Kultur Dokumente
Follow updates?
http://learningstatisticswithr.com/
https://twitter.com/lsrbook
Example:
Done.
quadruple <- function( x ) {
y <- x*4
return(y)
}
> quadruple( 9 )
[1] 36
> quadruple( x=c(2,3,4) )
[1] 8 12 16
If & else
amHappy <- function( day ) {
if( day=="Thursday" ) {
happy <-TRUE
} else {
happy <- FALSE
}
return( happy )
}
Loops
firstFivePowers <- function( x ) {
y <- vector()
for( i in 1:5 ) {
y[i] <- x^i
}
return(y)
}
> firstFivePowers( 2 )
[1] 2 4 8 16 32
> firstFivePowers( 3 )
[1]
3
9 27 81 243
R Markdown
# R markdown is neat
Sometimes its nice to combine programming with
human friendly words This is what R markdown
does. I write a whole bunch of human friendly
words, reminding myself of what Ive done. Then
I add a code block, which looks like this:
```{r}
age <- c(15, 20, 21, 21, 30)
print( mean(age) )
```
# define ages
Here it is in Rstudio...
Text processing
A few basics
> varNames <- names( expt )
> varNames
[1] "id"
"age"
"gender"
[5] "hormone"
"happy"
"sad"
"treatment"
A few basics
> varNames <- names( expt )
> varNames
[1] "id"
"age"
"gender"
[5] "hormone"
"happy"
"sad"
"treatment"
Concatenating strings
"AAA.id.BBB"
"AAA.gender.BBB"
"AAA.hormone.BBB"
"AAA.sad.BBB"
"AAA.age.BBB"
"AAA.treatment.BBB"
"AAA.happy.BBB"
Changing case
"AGE"
"HAPPY"
"GENDER"
"SAD"
"TREATMENT"
Trimming strings
> strtrim( varNames, 3 )
[1] "id" "age" "gen" "tre" "hor" "hap" "sad"
Trimming strings
> strtrim( varNames, 3 )
[1] "id" "age" "gen" "tre" "hor" "hap" "sad"
"reatment" "ormone"
Trimming strings
> strtrim( varNames, 3 )
[1] "id" "age" "gen" "tre" "hor" "hap" "sad"
"reatment" "ormone"
"AGE"
"HAPpy"
"GENder"
"SAD"
"TREatment"
"AGE"
"HAPpy"
"GENder"
"SAD"
"TREatment"
> paste(
toupper( strtrim( varNames,3 )),
substring( varNames, first=4 ),
sep=""
)
[1] "ID"
"AGE"
"GENder"
"TREatment"
[5] "HORmone"
"SAD" of these two
So... if "HAPpy"
we paste() the results
operations together...
> paste(
toupper( strtrim( varNames,3 )),
substring( varNames, first=4 ),
sep=""
)
[1] "ID"
[5] "HORmone"
"AGE"
"HAPpy"
"GENder"
"SAD"
"TREatment"
Splitting strings
"was"
"the"
"best"
"of"
"times"
"treatment" "happy"
"sad"
"treatment" "happy"
"sad"
"treatment" "happy"
"sad"
"treatment" "happy"
"sad"
"treatment" "happy"
"sad"
"treatment" "happy"
"sad"
"treatment" "happy"
> grep(
pattern = "a",
x = varNames,
fixed = TRUE
)
[1] 2 4 6 7
"sad"
> grep(
pattern = "[aeiou]",
x = varNames,
value = TRUE
)
[1] "id"
[5] "hormone"
"age"
"happy"
"treatment"
> grep(
pattern = "[aeiou]",
x = varNames,
value = TRUE
)
[1] "id"
[5] "hormone"
"age"
"happy"
"gender"
"sad"
"treatment"
> grep(
pattern = "[aeiou]",
x = varNames,
value = TRUE
)
[1] "id"
[5] "hormone"
"age"
"happy"
"gender"
"sad"
"treatment"
> gsub(
pattern = "[aeiou]",
replacement = ".",
x = varNames
)
[1] ".d"
[5] "h.rm.n."
".g."
"h.ppy"
"g.nd.r"
"s.d"
"tr..tm.nt"
Follow updates?
http://learningstatisticswithr.com/
https://twitter.com/lsrbook