我的代码是:
data$E<-ifelse(data$D==data$B, "b", ifelse(data$D==data$C, "c", "unknowwn"))
结果:
A B C D E
1 16 16 NA 16 b
2 20 NA 20 20 NA
3 24 NA NA 24 NA
但是我想要的是:
A B C D E
1 16 16 NA 16 b
2 20 NA 20 20 c
3 24 NA NA 24 unknowwn
有人知道如何解决这个问题吗? 谢谢!
答案 0 :(得分:1)
import pigpio
import time
class Buttons:
def __init__(self):
self.pi = pigpio.pi()
the_pins = [
{"pin":17, "handler":self.btnHandler17},
{"pin":22, "handler":self.btnHandler22},
{"pin":23, "handler":self.btnHandler23},
{"pin":27, "handler":self.btnHandler27}]
for x in the_pins:
pin = x["pin"]
self.pi.set_glitch_filter(pin, 20000)
self.pi.set_mode(pin, pigpio.INPUT)
self.pi.callback(pin, pigpio.FALLING_EDGE, x["handler"])
while True:
time.sleep(1)
def btnHandler17(self,pin,level,tick):
print("Button 17 Pressed",pin,level,tick)
def btnHandler22(self,pin,level,tick):
print("Button 22 Pressed",pin,level,tick)
def btnHandler23(self,pin,level,tick):
print("Button 23 Pressed",pin,level,tick)
def btnHandler27(self,pin,level,tick):
print("Button 27 Pressed",pin,level,tick)
myButtons = Buttons()
答案 1 :(得分:0)
您的情况有点复杂,因为您需要考虑B
,C
或D
列中是否包含NA
。因此,您可以尝试考虑将dplyr::case_when
用作:
已编辑:根据@A.Suliman
的建议,无需使用is.na
检查case_when
。
library(dplyr)
data %>% mutate( E = case_when(
D==B ~ "b",
D==C ~ "c",
TRUE ~ "Unknown"
))
# A B C D E
# 1 16 16 NA 16 b
# 2 20 NA 20 20 c
# 3 24 NA NA 24 Unknown
数据:
data <- read.table(text=
"A B C D
1 16 16 NA 16
2 20 NA 20 20
3 24 NA NA 24",
header = TRUE)