将列添加到R中的数据框 [英] Adding a column to a dataframe in R

查看:267
本文介绍了将列添加到R中的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框( df

 start     end
1    14379   32094
2   151884  174367
3   438422  449382
4   618123  621256
5   698271  714321
6   973394  975857
7   980508  982372
8   994539  994661
9  1055151 1058824
.   .       .
.   .       .
.   .       .

还有一个带有数值的长向量( vec )。

And a long vector with numeric values (vec).

我想在每行添加另一列,在 vec 。例如,第一行将具有 mean(vec [14379:32094])。我试过玩过 transform ,但无法完成这个简单的任务。

I would like to add to each row another column, with the mean of the values in the corresponding places in vec. for example, the first row will have mean(vec[14379:32094]). I have tried playing with transform but wasn't able to accomplish this simple task.

推荐答案

这是一个非常标准的用例, apply()

That is a pretty standard use case for apply():

R> vec <- 1:10
R> DF <- data.frame(start=c(1,3,5,7), end=c(2,6,7,9))
R> DF$newcol <- apply(DF,1,function(row) mean(vec[ row[1] : row[2] ] ))
R> DF
  start end newcol
1     1   2    1.5
2     3   6    4.5
3     5   7    6.0
4     7   9    8.0
R> 

您还可以使用 plyr 但是这里并不是真的需要超出基础R的功能。

You can also use plyr if you prefer but here is no real need to go beyond functions from base R.

这篇关于将列添加到R中的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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