R: apply-like function that returns a data frame?

前端 未结 1 564
青春惊慌失措
青春惊慌失措 2020-12-30 13:29

I want to apply a function to every row of a data frame. Using apply, the result is not itself a data frame again, it looks more like a list or matrix? (I don\'t know enough

相关标签:
1条回答
  • 2020-12-30 13:48

    You can use the apply family but, you're right, the result is either a matrix or a list. Not a big deal though to get back to a data.frame.

    Your function needs to return something consistent across columns (raw iris instead of iris[, 1:4] would not work below, because of iris$Species which is a factor with 3 levels where summary returns 6 numeric from a numeric column) and that's where a reproducible would help. Below, I used iris and summary:

    1. apply: as.data.frame(apply(iris[, 1:4], 2, summary))
    2. sapply: as.data.frame(sapply(iris[, 1:4], summary))
    3. lapply: do.call(cbind, lapply(iris[, 1:4], summary))
    0 讨论(0)
提交回复
热议问题