根据布尔值多列选择列值 - R.

时间:2018-05-06 14:39:33

标签: r

我的数据如下所示,

let main_string = textView2.text
let string_to_change = selectedTextWBU
let range = (main_string! as NSString).range(of: string_to_change)
let attributedString = NSMutableAttributedString(string: main_string!, attributes: [kCTFontAttributeName as NSAttributedStringKey : font])

if selectedTextWBU == ""{

}else{

    //highlight
    if sender.tag == 1{
        print("SELECTEDTEXTWBU ==  \(selectedTextWBU)")
        textView2.attributedText = attributedString

        //italic
    }else if sender.tag == 2{
        attributedString.addAttribute(kCTFontAttributeName as 
            NSAttributedStringKey, value: italicsFont, range: range)          
        textView2.attributedText = attributedString

        //bold
    }else if sender.tag == 3{
        attributedString.addAttribute(kCTFontAttributeName as NSAttributedStringKey, value: boldFont, range: range)
        textView2.attributedText = attributedString

    }

}

我期待输出如下

df=data.frame("X1" = c(1, 0, 0), "X2" = c(0, 0, 1), "X3" = c(0, 1, 0),
           "T1" = c(21, 20, 15), "T2" = c(35, 16, 19), "T3" = c(22, 32, 16))

X1  X2  X3  T1  T2  T3
1   0   0   **21**  35  22
0   0   1   20  16  **32**
0   1   0   15  **19**  16

如您所见,从T1,T2和T3只能根据X1,X2和X3中的布尔值选择这些值。

我使用for循环编写了一个愚蠢的代码,寻找最好的方法..

2 个答案:

答案 0 :(得分:5)

我们将前三列(二进制列)与接下来的三列(0 *任意值= 0)相乘,得到pmax(因为每行只有一个非零值)来创建'T'栏

cbind(df[1:3], T = do.call(pmax, df[1:3]* df[4:6]))
#  X1 X2 X3  T
#1  1  0  0 21
#2  0  0  1 32
#3  0  1  0 19

答案 1 :(得分:3)

x = c("X1", "X2", "X3")
t = c("T1", "T2", "T3")
df[, "T"] = rowSums(df[, x] * df[, t])

说明:

当你乘以df[, x] * df[, t]时,你会得到你想要的值:

>>> df[, x] * df[, t]
  X1 X2 X3
1 21  0  0
2  0  0 32
3  0 19  0

然后只需rowSums来获取值

[1] 21 32 19