Code
myprint <- function(x) {
print(x)
}
R
brush-up
myprint <- function(x) {
print(x)
}
myprint(2)
[1] 2
myprint()
Error in myprint(): argument "x" is missing, with no default
myprint_def <- function(x = "no name") {
print(x)
}
myprint_def()
[1] "no name"
for
loopdata.frame
:first_name | last_name | gender |
---|---|---|
Hermione | Granger | female |
Ron | Weasley | male |
Harry | Potter | male |
Write a function that takes such a data.frame
as a argument and that will print the last name for each row.
print_last_name <- function(x) {
for (i in 1:nrow(x)) {
print(as.character(x[i, "last_name"]))
}
}
print_last_name(hp_df)
[1] "Granger"
[1] "Weasley"
[1] "Potter"
while
statementwhile
statement.print_last_name_while <- function(x) {
i <- 1
while (i <= nrow(x)) {
print(as.character(x[i, "last_name"]))
i <- i + 1
}
}
print_last_name_while(hp_df)
[1] "Granger"
[1] "Weasley"
[1] "Potter"
if
/else
statementprint_last_name_if <- function(x) {
for (i in 1:nrow(x)) {
if (x[i, "gender"] == "female") {
print(as.character(x[i, "last_name"]))
} else if (x[i, "gender"] == "male") {
print(as.character(x[i, "first_name"]))
}
}
}
print_last_name_if(hp_df)
[1] "Granger"
[1] "Ron"
[1] "Harry"
There are only two hard things in Computer Science:
- cache invalidation, and
- naming things.
– Phil Karlton