在R中生成具有多个条件的列值 [英] generate column values with multiple conditions in R
问题描述
我有一个数据框z
,我想基于z
的两个旧列的值创建一个新列.以下是该过程:
I have a dataframe z
and I want to create the new column based on the values of two old columns of z
. Following is the process:
>z<-cbind(x=1:10,y=11:20,t=21:30)
> z<-as.data.frame(z)
>z
x y t
1 1 11 21
2 2 12 22
3 3 13 23
4 4 14 24
5 5 15 25
6 6 16 26
7 7 17 27
8 8 18 28
9 9 19 29
10 10 20 30
#生成列q
,该列等于列t
的值乘以4(如果x=3
),而对于其他值x
,则等于列t
的值.
# generate the column q
which is equal to the values of column t
times 4 if x=3
and for other values of x
, it is equal to the values of column t
.
for (i in 1:nrow(z)){
z$q[i]=if (z$x[i]==4) 4*z$t[i] else z$t[i]}
但是,我的问题是我想应用多个条件:
But, my problem is that I want to apply multiple conditions:
例如,我想得到这样的东西:
For example, I want to get something like this:
(If x=2, q=t*2; x=4, q=t*4; x=7, q=t*3; for other it is equal to t)
> z
x y t q
1 1 11 21 21
2 2 12 22 44
3 3 13 23 23
4 4 14 24 96
5 5 15 25 25
6 6 16 26 26
7 7 17 27 81
8 8 18 28 28
9 9 19 29 29
10 10 20 30 30
如何使用循环或任何其他方法获得第二个输出?
How do I get the second output using the loops or any other method?
推荐答案
生成多重矢量:
tt <- rep(1, max(z$x))
tt[2] <- 2
tt[4] <- 4
tt[7] <- 3
这是您的新列:
> z$t * tt[z$x]
[1] 21 44 23 96 25 26 81 28 29 30
> z$q <- z$t * tt[z$x]
> z
x y t q
1 1 11 21 21
2 2 12 22 44
3 3 13 23 23
4 4 14 24 96
5 5 15 25 25
6 6 16 26 26
7 7 17 27 81
8 8 18 28 28
9 9 19 29 29
10 10 20 30 30
如果z$x
中的值为负,则此方法将无效.
This will not work if there are negative values in z$x
.
已编辑
这是上面的概括,其中一个函数用于生成乘数向量.实际上,我们基于参数创建了一个函数.
Here is a generalization of the above, where a function is used to generate the multiplier vector. In fact, we create a function based on parameters.
我们要转换以下值:
2 -> 2
4 -> 4
7 -> 3
否则将采用默认值1.
Otherwise a default of 1 is taken.
这是一个生成所需函数的函数:
Here is a function which generates the desired function:
f <- function(default, x, y) {
x.min <- min(x)
x.max <- max(x)
y.vals <- rep(default, x.max-x.min+1)
y.vals[x-x.min+1] <- y
function(z) {
result <- rep(default, length(z))
tmp <- z>=x.min & z<=x.max
result[tmp] <- y.vals[z[tmp]-x.min+1]
result
}
}
这是我们的用法:
x <- c(2,4,7)
y <- c(2,4,3)
g <- f(1, x, y)
g
是我们想要的功能.应该清楚的是,可以通过x
和y
参数将任何映射提供给f
.
g
is the function that we want. It should be clear that any mapping can be supplied via the x
and y
parameters to f
.
g(z$x)
## [1] 1 2 1 4 1 1 3 1 1 1
g(z$x)*z$t
## [1] 21 44 23 96 25 26 81 28 29 30
应该清楚,这仅适用于整数值.
It should be clear this only works for integer values.
这篇关于在R中生成具有多个条件的列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!