Reputation: 2617
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
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 t
ranspose step by applying the function column-wise (margin=2
)
data.frame(apply(df, 2,my_f))
Upvotes: 2
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
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
Reputation: 12559
Here is a solution without any apply-function:
df[] <- my_f(as.matrix(df))
Upvotes: 4