简体   繁体   English

根据其他列数据框r中的值添加列

[英]add column based on values in other columns data frame r

I'm curious about how to solve this problem. 我很好奇如何解决这个问题。 I have data frame like this: 我有这样的数据框:

a    b    
1    0    
1    0
0    1
1    1
0    0
1    0   

Then the output has an extra column based on values of "a" and "b": 然后输出有一个基于“a”和“b”值的额外列:

if(a==1&b==1) c=1, if(a==1&b==0) c=2, if(a==0&b==1) c=3, else c=4. if(a == 1&b == 1)c = 1,if(a == 1&b == 0)c = 2,if(a == 0&b == 1)c = 3,否则c = 4。

a    b    c
1    0    2
1    0    2
0    1    3
1    1    1
0    0    4
1    0    2

Any thoughts? 有什么想法吗? I don't to write a for loop with nested if-else, how could we go vectorize? 我不用嵌套的if-else写一个for循环,我们怎么去vectorize? Thanks! 谢谢!

interaction is made for this: 为此进行了interaction

c(4,2,3,1)[interaction(df)]
#[1] 2 2 3 1 4 2

This will also work: 这也有效:

library(dplyr)
inner_join (df, cbind(expand.grid(0:1, 0:1), c=c(4, 2, 3, 1)), 
                by=c('a'='Var1', 'b'='Var2'))

  a b c
1 1 0 2
2 1 0 2
3 0 1 3
4 1 1 1
5 0 0 4
6 1 0 2

With a little bit of linear algebra: 用一点线性代数:

we need to solve for x,y from the equation c = 4 - x a - y b we can see x = 2, y = 1 is the solution given the set of variable values 我们需要从等式c = 4 - x a - y b求解x,y我们可以看到x = 2,y = 1是给定变量值集的解

 a  b c
 0  0 4
 1  0 2
 0  1 3
 1  1 1

or we can use the limSolve to solve this over-determined set of equations: 或者我们可以使用limSolve来解决这个过度确定的方程组:

library(limSolve)
res <- Solve(as.matrix(expand.grid(0:1, 0:1)), 4-c(4, 2, 3, 1))
res
Var1 Var2  # a = Var1, b = Var2
   2    1

Hence, we have: 因此,我们有:

df$c <- 4 - res[1]*df$a - res[2]*df$b
df
a b c
1 1 0 2
2 1 0 2
3 0 1 3
4 1 1 1
5 0 0 4
6 1 0 2

Map your desired c-values to a vector and use a and b values as indices (increment by 1 for 1-based indexing). 将您想要的c值映射到向量,并使用a和b值作为索引(对于基于1的索引,递增1)。

foo <- data.frame(a=c(1,1,0,1,0,1), b=c(0,0,1,1,0,0))

data.frame(foo, c=c(4:1)[foo$a*2 + foo$b + 1])

#   a b c
# 1 1 0 2
# 2 1 0 2
# 3 0 1 3
# 4 1 1 1
# 5 0 0 4
# 6 1 0 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM