1

I have a dataframe and I would like to use a custom function to add multiple new columns to that dataframe. These new columns will be some function of an existing column, but they require the use of a custom function.

I am currently trying to have my custom function return the results in a list, which I then parse into separate columns. This sometimes works by returning a vector of lists, but sometimes this returns a matrix, in which case I get an error like

Error in $<-.data.frame(*tmp*, "z", value = list(1, 2, 2, 3, 3, 4)) : replacement has 2 rows, data has 3

Below is a sample of what I am trying to do.

sample_func <- function(number)
{
list(w = number + 1, u = number + 2)
}

data = data.frame(x = c(1,2,3), y= c(5,6,7))
data$z = sapply(c(1,2,3),sample_func)
data$w = sapply(data$z,"[[","w")
data$u = sapply(data$z,"[[","u")

1 Answer 1

2

The function sapply automatically simplifies the result. In this case, you obtain a matrix. You can avoid this behaviour with the argument simplify = FALSE. But it's easier to use lapply because this function doesn't try to simplify the result.

The command

tmp <- lapply(c(1,2,3), sample_func)

returns a list of lists:

[[1]]
[[1]]$w
[1] 2

[[1]]$u
[1] 3


[[2]]
[[2]]$w
[1] 3

[[2]]$u
[1] 4


[[3]]
[[3]]$w
[1] 4

[[3]]$u
[1] 5

You can use the following command to add the new columns to your data frame:

cbind(data, do.call(rbind, tmp))

#   x y w u
# 1 1 5 2 3
# 2 2 6 3 4
# 3 3 7 4 5

Update to address comment:

If possible, you can modify the function to return a data frame.

sample_func <- function(number)
{
  data.frame(w = number + 1, u = number + 2)
}

tmp <- lapply(c(1,2,3), sample_func)

cbind(data, do.call(rbind, tmp))

The result will be a data frame with numeric columns.

Sign up to request clarification or add additional context in comments.

1 Comment

This makes w and u lists, which I then have to convert to numeric. Is there a better way than doing data$w <- as.numeric(data$w)?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.