我想根据行中的值在 data.frame 中创建新列。
如果“type”不等于“a”,则我的“new.area”列应包含来自“a”类型的“area”的数据。这是针对多个“距离”的。
Example:
# create data frame
distance<-rep(seq(1,5, by = 1),2)
area<-c(11:20)
type<-rep(c("a","b"),each = 5)
# check data.frame
(my.df<-data.frame(distance, area, type))
distance area type
1 1 11 a
2 2 12 a
3 3 13 a
4 4 14 a
5 5 15 a
6 1 16 b
7 2 17 b
8 3 18 b
9 4 19 b
10 5 20 b
我想创建一个新列(my.df$new.area
),其中对于行中的每个“距离”,都会有“a”类型的“面积”值。
distance area type new.area
1 1 11 a 11
2 2 12 a 12
3 3 13 a 13
4 4 14 a 14
5 5 15 a 15
6 1 16 b 11
7 2 17 b 12
8 3 18 b 13
9 4 19 b 14
10 5 20 b 15
我知道如何手动为单行进行此操作:
my.df$new.area[my.df$distance == 1 ] <- 11
但如何自动制作呢?
这是使用索引子集的基本 R 解决方案([
) and match
:
my.df$new.area <- with(my.df, area[type == "a"][match(distance, distance[type == "a"])])
返回
my.df
distance area type new.area
1 1 11 a 11
2 2 12 a 12
3 3 13 a 13
4 4 14 a 14
5 5 15 a 15
6 1 16 b 11
7 2 17 b 12
8 3 18 b 13
9 4 19 b 14
10 5 20 b 15
area[type == "a"]
提供可能性的向量。match
用于通过距离变量返回该向量的索引。with
用于避免重复使用my.df$
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)