Skip to content

Instantly share code, notes, and snippets.

@tomer-ben-david
Created January 20, 2018 10:11
Show Gist options
  • Save tomer-ben-david/7073355f9ca15ce3c3b09c3e7df29cd5 to your computer and use it in GitHub Desktop.
Save tomer-ben-david/7073355f9ca15ce3c3b09c3e7df29cd5 to your computer and use it in GitHub Desktop.
apply function to matrix
> df <- data.frame(x=c("spam", "spam", "ham"), y=c("some mail", "some other mail", "some third mail"))
> add.string.func <- function(somestr) { paste("prefix-", somestr, "-postfix", sep = "") }
> df[1,]
x y
1 spam some mail
> df[,1]
[1] spam spam ham
Levels: ham spam
> apply(X = df[1,], add.string.func, MARGIN = 1)
1
[1,] "prefix-spam-postfix"
[2,] "prefix-some mail-postfix"
> apply(X = as.matrix(df[,1]), add.string.func, MARGIN = 1)
[1] "prefix-spam-postfix" "prefix-spam-postfix" "prefix-ham-postfix"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment