[英]Adding new variable to each element of a list of data.frames
I have a list of data frames ( C ). 我有一个数据帧列表(C)。 I want to add a new variable "d" to each data frame, wich'd be the sum of "a" and "b".
我想向每个数据帧添加一个新变量“ d”,该变量应为“ a”和“ b”的总和。 Here's a short example.
这是一个简短的例子。
A<-data.frame(1:10, 101:110, 201:210)
colnames(A)=c("a","b", "c")
B<-data.frame(11:20, 111:120, 211:220)
colnames(B)=c("a","b", "c")
C<-list(A, B)
I've tried this, but i think there may be something simpler, specially considering the last part of the line ( value= (("["(C[[x]][1]))) + ("["(C[[x]][2])) )
我已经尝试过了,但是我认为可能更简单一些,特别是考虑该行的最后部分
( value= (("["(C[[x]][1]))) + ("["(C[[x]][2])) )
lapply(seq(C), function(x) "[[<-" (C[[x]], 3, value= (("["(C[[x]][1]))) + ("["(C[[x]][2])))
Any ideas? 有任何想法吗? And BTW, how can i choose the name of the variable created?
顺便说一句,我如何选择创建的变量的名称? Thanx in advance
提前感谢
This should be easy using within
: within
使用起来应该很容易:
out <- lapply(C, function(x) within(x, d <- a + b))
Here's the result: 结果如下:
> str(out)
List of 2
$ :'data.frame': 10 obs. of 4 variables:
..$ a: int [1:10] 1 2 3 4 5 6 7 8 9 10
..$ b: int [1:10] 101 102 103 104 105 106 107 108 109 110
..$ c: int [1:10] 201 202 203 204 205 206 207 208 209 210
..$ d: int [1:10] 102 104 106 108 110 112 114 116 118 120
$ :'data.frame': 10 obs. of 4 variables:
..$ a: int [1:10] 11 12 13 14 15 16 17 18 19 20
..$ b: int [1:10] 111 112 113 114 115 116 117 118 119 120
..$ c: int [1:10] 211 212 213 214 215 216 217 218 219 220
..$ d: int [1:10] 122 124 126 128 130 132 134 136 138 140
You could, then, store out
as C
(ie, C <- out
) to replace the original list. 你可以的话,存储
out
作为C
(即C <- out
),以取代原来的列表中。 I just use out
here to show you what is going on. 我只是
out
这里out
,向您展示发生了什么。
Or using cbind
或使用
cbind
C <- lapply(C, function(x) cbind(x, d = x[["a"]] + x[["b"]]))
Or using rowSums
或使用
rowSums
C <- lapply(C, function(x) cbind(x, d = rowSums(x[1:2])))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.