对R中的数据帧中的每一行应用一个函数 [英] Apply a function to each row in a data frame in R

查看:133
本文介绍了对R中的数据帧中的每一行应用一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何将函数应用于R中的矩阵(或数据帧)的每一行, a>

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

R - 如何使用df的每一行中的多个参数从每行数据帧上调用类似应用的函数

我想对数据框中的每一行应用一个函数,但是,R默认将其应用于每一列。如何强制它否则?

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 

我想要像

1   2
2   0
3   3


推荐答案

你想要 apply (见文档)。 apply(var,1,fun)将适用于行, apply(var,2,fun)将适用于列。

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

这篇关于对R中的数据帧中的每一行应用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆