Apply a function to each row in a data frame in R [duplicate]

主宰稳场 提交于 2019-12-04 09:56:04

问题


Possible Duplicate:
how to apply a function to every row of a matrix (or a data frame) in R

R - how to call apply-like function on each row of dataframe with multiple arguments from each row of the df

I want to apply a function to each row in a data frame, however, R applies it to each column by default. How do I force it otherwise?

> a = as.data.frame(list(c(1,2,3),c(10,0,6)),header=T)
> a
  c.1..2..3. c.10..0..6.
1          1          10
2          2           0
3          3           6
> sapply(a,min)
 c.1..2..3. c.10..0..6. 
          1           0 

I wanted something like

1   2
2   0
3   3

回答1:


You want apply (see the docs for it). apply(var,1,fun) will apply to rows, apply(var,2,fun) will apply to columns.

> apply(a,1,min)
[1] 1 0 3


来源:https://stackoverflow.com/questions/5330146/apply-a-function-to-each-row-in-a-data-frame-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!