15

UPDATE: before, I used the paste function as an example instead of an arbitrary myFun function. That problem was slightly easier, because paste can actually operate on vectors, while myFun can not.

I would like to apply my own function element-wise to every element in a data.frame, and get the modified data.frame as a return value.

Example:

> df <- data.frame(c(1,2,3), c(2,3,4))
> df
  c.1..2..3. c.2..3..4.
1          1          2
2          2          3
3          3          4
> df_x <- magical_apply_function(df, function(x) myFun
> df_x
  c.1..2..3. c.2..3..4.
1         myFun(1)         myFun(2)
2         myFun(2)         myFun(3)
3         myFun(3)         myFun(4)

I'm completely baffled to not be able to find the answer to this problem anywhere on the internet. Most resources talk about apply, lapply, and sapply but those only work on vectors/lists and they only return lists.

Are for loops really the only way to go here?

3
  • 1
    Just use lapply, q.v. the @akrun answer below. Commented Feb 7, 2018 at 11:06
  • Notwithstanding the solutions below I'm baffled why you are baffled. It's the raison d'être of data.frames to collect disparate data. Although paste works here if you can apply the function to the whole DF then usually it should be a matrix. Commented Feb 7, 2018 at 11:36
  • bonus: the function to be applied can NOT handle vectors Commented Feb 7, 2018 at 11:46

4 Answers 4

17
df <- data.frame(c(1,2,3), c(2,3,4))
df[] <- lapply(df, function(x) paste(x,"x", sep=""))
df

df[] preserves the dataframe's structure.

3
  • when I do something similar to this (same rationale, different function(x)) I get an Error stating that arguments imply differing number of rows: 3877, 3890, 3884, 3925, 4024, 3942, 2758, 4042, 4796, 7297 I'm using an unlist() function inside of myFun and I think it's screwing up the lengths, because its operating on a list of lists. Commented Feb 7, 2018 at 12:14
  • holy moly, indeed, the unlist() function unlists more than just one level of listing. Commented Feb 7, 2018 at 12:16
  • 1
    the solution to that second problem is to use unlist() with option recursive=F and then everything works out. Commented Feb 7, 2018 at 12:40
11

We can either use mutate_all from dplyr

library(dplyr)
df %>% 
     mutate_all(funs(paste0(., "x")))

Or with lapply from base R and convert it to data.frame

data.frame(lapply(df, paste0,  "x"))
9

Can you not use apply(df, c(1,2), myFun)? Using the c(1,2) will apply the function to each item in your dataframe individually:

MARGIN a vector giving the subscripts which the function will be applied over. E.g., for a matrix 1 indicates rows, 2 indicates columns, c(1, 2) indicates rows and columns.

> temp<-data.frame(le=LETTERS[1:3], nu=20:22)
> temp
  le nu
1  A 20
2  B 21
3  C 22
> apply(temp, c(1,2), function(x) {gsub('d',x,'d1d1')})
     le     nu      
[1,] "A1A1" "201201"
[2,] "B1B1" "211211"
[3,] "C1C1" "221221"

The function isn't used correctly if you apply the function by rows:

> apply(temp, 1, function(x) {gsub('d',x,'d1d1')})
[1] "A1A1" "B1B1" "C1C1"
Warning messages:
1: In gsub("d", x, "d1d1") :
  argument 'replacement' has length > 1 and only the first element will be used
2: In gsub("d", x, "d1d1") :
  argument 'replacement' has length > 1 and only the first element will be used
3: In gsub("d", x, "d1d1") :
  argument 'replacement' has length > 1 and only the first element will be used
2
  • The curly brackets can be omitted apply(temp, c(1,2), function(x) gsub('d',x,'d1d1'))
    – Julien
    Commented Jul 27, 2022 at 6:02
  • 1
    By the way, this solution is the only one in the thread that really answers the question
    – Julien
    Commented Jul 27, 2022 at 6:06
3

See also these purrr functions

library(purrr)
modify(df,paste0,"x") # output is of the same type input, so `data.frame` here

#   c.1..2..3. c.2..3..4.
# 1         1x         2x
# 2         2x         3x
# 3         3x         4x

map_df(df,paste0,"x") # output is always tibble

# # A tibble: 3 x 2
#   c.1..2..3. c.2..3..4.
#        <chr>      <chr>
# 1         1x         2x
# 2         2x         3x
# 3         3x         4x
3
  • Does modify work cell by cell ? I thought it works across columns
    – Julien
    Commented Jul 27, 2022 at 6:04
  • 1
    You're right, but the question was updated after answers and first used paste, and the solution which was accepted works the same. The apply solution you commented on doesn't really answer the question because it returns a matrix, but df[] <- apply(...) (with square brackets) might do the trick. Commented Jul 27, 2022 at 11:18
  • Still, this solution is the closest to a good answer to the current question
    – Julien
    Commented Jul 27, 2022 at 11:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.