我有一个包含3列的数据框,如下所示 I / p数据框
A = c("(0_22),(0_25),(1_29)","(1_34),(1_38),(0_40)","(0_07),(0_09),(0_10),(0_13)","(1_47),(1_49),(1_53),(1_57)")
zero =c(5,NA,6,NA)
one = c(NA,4,NA,10)
df = data.frame(A,zero,one)
O / p数据框
A = c("(0_22),(0_25),(1_29)","(1_34),(1_38),(0_40)","(0_07),(0_09),(0_10),(0_13)","(1_47),(1_49),(1_53),(1_57)")
zero =c(5,NA,6,NA)
one = c(NA,4,NA,10)
required_val = c("(1_29)","(0_40)",'','')
df = data.frame(A,zero,one,required_val)
如何根据零和一个变量
从变量“A”获取列“required_val”即如果var“0”大于0则消除由(0_)
组成的字符串
如果var“one”大于0则消除由(1 _)
答案 0 :(得分:4)
这基本上是一个模式匹配问题:
sass-to-css.js
答案 1 :(得分:1)
这是另一种解决方案,
required_val<-NA
for (i in 1:length(A))
{
required_val[i]<-""
if(!is.na(zero[i]) & grepl("1_",A[i]))
{
required_val[i]<-substr(A[i],unlist(gregexpr('1_',A[i]))[1],unlist(gregexpr('1_',A[i]))[1]+3)
} else if (!is.na(one[i]) & grepl('0_',A[i]))
{
required_val[i]<-substr(A[i],unlist(gregexpr('0_',A[i]))[1],unlist(gregexpr('0_',A[i]))[1]+3)
}
}
df = data.frame(A,zero,one,required_val)
答案 2 :(得分:1)
使用应用
#example data
df1 <- data.frame(A = c("(0_22),(0_25),(1_29)","(1_34),(1_38),(0_40)","(0_07),(0_09),(0_10),(0_13)","(1_47),(1_49),(1_53),(1_57)"),
zero = c(5, NA, 6, NA),
one = c(NA, 4, NA, 10),
stringsAsFactors = FALSE)
cbind(df1,
required_val = apply(df1, 1,
function(i){
ix <- which.max(as.numeric(i[2:3]) > 1) - 1
x <- unlist(strsplit(i[1], ","))
x <- x[ !grepl(paste0("^\\(", ix), x) ]
if(length(x) == 0) {x <- ""}
#return
x
}))
# A zero one required_val
# 1 (0_22),(0_25),(1_29) 5 NA (1_29)
# 2 (1_34),(1_38),(0_40) NA 4 (0_40)
# 3 (0_07),(0_09),(0_10),(0_13) 6 NA
# 4 (1_47),(1_49),(1_53),(1_57) NA 10