mat
mat

Reputation: 2617

R: Applying a function to every element of a dataframe

For example, lets use the following dataframe composed of strings:

df <- data.frame(X = LETTERS[1:3], Y = LETTERS[4:6], row.names = c("r1", "r2", "r3"), stringsAsFactors = F)

> df
   X Y
r1 A D
r2 B E
r3 C F

Now, I'd like to apply this function to each element of the dataframe:

my_f <- function(x) paste0(x, x)

Which should produce this result:

>df
    X  Y
r1 AA DD
r2 BB EE
r3 CC FF

I've been using nested for loops:

for (i in 1:dim(df)[1]) {
    for (j in 1:dim(df)[2]) {
        df[i, j] = my_f(df[i, j])
    }
}

I wonder if there is a shorter/faster way to achieve the same result? Note that the ouput must be a dataframe with the same rows' and colums' names.

Upvotes: 1

Views: 2397

Answers (4)

Ronak Shah
Ronak Shah

Reputation: 388807

You already have the answer.

You can apply your function my_f for every element rowwise (margin = 1)

data.frame(t(apply(df, 1,my_f)))

#    X1 X2
#r1 AA DD
#r2 BB EE
#r3 CC FF

And as @m0h3n suggested, you can avoid the transpose step by applying the function column-wise (margin=2)

data.frame(apply(df, 2,my_f))

Upvotes: 2

Arun kumar mahesh
Arun kumar mahesh

Reputation: 2359

Using for loops

for(i in 1:nrow(df)){
  df$X[i] <- paste0(df$X[i],df$X[i],collapse = "")
  df$Y[i] <- paste0(df$Y[i],df$Y[i],collapse = "")
}

print(df)

  X  Y
r1 AA DD
r2 BB EE
r3 CC FF

Upvotes: 1

akrun
akrun

Reputation: 886938

We can use strrep by looping over the columns of dataset with lapply. The [] will restore the same 'data.frame' structure.

df[] <- lapply(df, strrep,2)
df
#   X  Y
#r1 AA DD
#r2 BB EE
#r3 CC FF

Upvotes: 6

jogo
jogo

Reputation: 12559

Here is a solution without any apply-function:

df[] <- my_f(as.matrix(df))

Upvotes: 4

Related Questions